如何搜索与特定模式匹配的URL



所以我的目标是制作一个python脚本,读取电子邮件,然后选择其中的特定链接,然后在web浏览器中打开。

但现在我被困在了获取所有URL链接的部分。但我想把它们过滤到一个特定的特定的URL包含"/user/cm-l.php?",但在问号之后,您会得到一个随机生成的链接。

是否有人知道如何修复此问题或编辑脚本以仅筛选包含该部分的URL?

我尝试了一些re.search/findall/match,但我无法使它工作,所以它只能过滤那个URL。

import imaplib 
import email
import re
# imap and user credentials.
mail = imaplib.IMAP4_SSL('imap.domain.com')
mail.login('username@domain.com', 'password')
mail.list()
# connect to right mailbox inside inbox.
mail.select("inbox")
result, data = mail.search(None, "ALL")
# data is a list.
ids = data[0]
# ids is a space separated string.
id_list = ids.split()
# changes which e-mail to read. '-1': gets the latest e-mail.
latest_email_id = id_list[6]
result, data = mail.fetch(latest_email_id, "(RFC822)")
raw_email = data[0][1]
raw_email = str(raw_email)
# this will search al the urls in an email.
def Find(string):
regex = r"(?i)b((?:https?://|wwwd{0,3}[.]|[a-z0-9.-]+[.][a-z]{2,4}/user)(?:[^s()<>]+|(([^s()<>]+|(([^s()<>]+)))*))+(?:(([^s()<>]+|(([^s()<>]+)))*)|[^s`!()[]{};:'".,<>?«»“”‘’]))"
url = re.findall(regex,string)      
return [x[0] for x in url] 
# prints all of the URLs.
print(Find(raw_email))

通过应用组(..)定义正则表达式模式,您可以找到具有可选前缀和后缀的精确字符串。CCD_ 4包括三组。

以下示例显示了如何访问提取的内容。

import re
mailstring = """
/user/cm-l.php?
some link : /main/home/user/cm-l.php?
link with suffix /user/cm-l.php?345TfvbzteW4rv#!_
"""

def Find(string):
pattern = r'([a-zA-Z/]*?)(/user/cm-l.php?)(.*)?'
for idx,match in enumerate(re.findall(pattern,string)):
print(f'### Match {idx}')
print('full= ',''.join(match))
print('0= ',match[0])
print('1= ',match[1]) # match[1] is the base url
print('2= ',match[2])
Find(mailstring)
'''
### Match 0
full=  /user/cm-l.php?
0=  
1=  /user/cm-l.php?
2=  
### Match 1
full=  /main/home/user/cm-l.php?
0=  /main/home
1=  /user/cm-l.php?
2=  
### Match 2
full=  /user/cm-l.php?345TfvbzteW4rv#!_
0=  
1=  /user/cm-l.php?
2=  345TfvbzteW4rv#!_
'''

最新更新