簡體   English   中英

如何將URL與python正則表達式匹配?

[英]How to match URLs with python regular expression?

我的問題是,我希望匹配HTML代碼中的URL,如下所示: href='example.com'或使用" ,但我只想提取實際的URL。我嘗試匹配它,然后使用數組魔術只獲得數組,但由於正則表達式匹配是貪婪的 ,如果有超過1個有理匹配,則會有更多從一個'開始並以另一個URL結束' 。什么正則表達式適合我的需要?

我建議不要使用正則表達式來解析HTML。 如果你使用像beautifulsoup這樣的東西,你的生活會更容易!

它就像這樣簡單:

from BeautifulSoup import BeautifulSoup

HTML = """<a href="https://firstwebsite.com">firstone</a><a href="https://secondwebsite.com">Ihaveurls</a>"""

s = BeautifulSoup(HTML)

for href in s.find_all('a', href=True): print("My URL: ", href['href'])

如果您希望它使用正則表達式而不是使用其他python庫來解決它。 這是解決方案。

import re
html = '<a href="https://www.abcde.com"></a>'
pattern = r'href=\"(.*)\"|href=\'(.*)\''
multiple_match_links = re.findall(pattern,html)
if(len(multiple_match_links) == 0):
     print("No Link Found")
else:
     print([x for x in list(multiple_match_links[0]) if len(x) > 0][0])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM