正则expression式在Python中的string中查找url

可能重复:
什么是最好的正则expression式来检查一个string是否是一个有效的URL?

考虑一个string如下:

string = "<p>Hello World</p><a href="http://example.com">More Examples</a><a href="http://example2.com">Even More Examples</a>" 

我怎么能用Python在锚标签的href里面提取URL呢? 就像是:

 >>> url = getURLs(string) >>> url ['http://example.com', 'http://example2.com'] 

谢谢!

 import re url = '<p>Hello World</p><a href="http://example.com">More Examples</a><a href="http://example2.com">Even More Examples</a>' urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', url) >>> print urls ['http://example.com', 'http://example2.com'] 

最好的答案是:

不要使用正则expression式

在接受答案中的expression错过了许多情况。 除此之外, URLs中可以包含unicode字符 。 你想要的正则expression式就在这里 ,看完之后,你可能会得出这样的结论,毕竟你并不是真的想要它。 最正确的版本是一万个字符长。

parsingHTML代替

除此之外,以下是您实际表明的目标:“提取锚标签的href内的URL”。 这是parsingHTML。 尽pipe编写一个正则expression式非常简单,它将抓住<a href=之间的任何值。

 >>> s = '<p>Hello World</p><a href="http://example.com">More Examples</a><a href="http://example2.com">Even More Examples</a>' >>> re.findall('<a href="?\'?([^"\'>]*)', s) ['http://example.com', 'http://example2.com'] 

这真的只适用于一个一次性的黑客行为的事情。 如果在任何时候,你认为你可能只是为了你自己的随意目的而去做任何事情 ,你现在应该多花两分钟时间来使用一个合适的parsing器。

Python附带的内置工具使得这个工作变得非常简单:下面是HTMLParser的一个非常简单的子类,它可以实现你想要的function。

 from html.parser import HTMLParser class MyParser(HTMLParser): def __init__(self, output_list=None): HTMLParser.__init__(self) if output_list is None: self.output_list = [] else: self.output_list = output_list def handle_starttag(self, tag, attrs): if tag == 'a': self.output_list.append(dict(attrs).get('href')) 

testing:

 >>> p = MyParser() >>> p.feed(s) >>> p.output_list ['http://example.com', 'http://example2.com'] 

你甚至可以创build一个接受string,调用feed并返回output_list的新方法。 简而言之,这是一个比RE更强大和更可扩展的方式来从HTML中提取信息。

对于许多任务,使用美丽的汤更容易:

 >>> from bs4 import BeautifulSoup as Soup >>> html = Soup(s, 'html.parser') # Soup(s, 'lxml') if lxml is installed >>> [a['href'] for a in html.find_all('a')] ['http://example.com', 'http://example2.com']