简体   繁体   English

如何将URL与python正则表达式匹配?

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

我的问题是,我希望匹配HTML代码中的URL,如下所示: href='example.com'或使用" ,但我只想提取实际的URL。我尝试匹配它,然后使用数组魔术只获得数组,但由于正则表达式匹配是贪婪的 ,如果有超过1个有理匹配,则会有更多从一个'开始并以另一个URL结束' 。什么正则表达式适合我的需要?

I would recommend NOT using regex to parse HTML. 我建议不要使用正则表达式来解析HTML。 Your life will be much easier if you use something like beautifulsoup ! 如果你使用像beautifulsoup这样的东西,你的生活会更容易!

It's as easy as this: 它就像这样简单:

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'])

In case if you want it to solve it using regular expression instead of using other libraries of python. 如果您希望它使用正则表达式而不是使用其他python库来解决它。 Here is the solution. 这是解决方案。

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