-2

我需要 python 正则表达式从 html 中提取 url,例如 html 代码:

<a href=""http://a0c5e.site.it/r"" target=_blank><font color=#808080>MailUp</font></a>
<a href=""http://www.site.it/prodottiLLPP.php?id=1"" class=""txtBlueGeorgia16"">Prodotti</a>
<a href=""http://www.site.it/terremoto.php"" target=""blank"" class=""txtGrigioScuroGeorgia12"">Terremoto</a>
<a class='mini' href='http://www.site.com/remove/professionisti.aspx?Id=65&Code=xhmyskwzse'>clicca qui.</a>`

我只需要提取:

 http://a0c5e.site.it/r
 http://www.site.it/prodottiLLPP.php?id=1
 http://www.site.it/terremoto.php
 http://www.site.com/remove/professionisti.aspx?Id=65&Code=xhmyskwzse
4

3 回答 3

2

正则表达式可能会解决您的问题,但请考虑使用 BeautifulSoup

>>> html = """<a href="http://a0c5e.site.it/r" target=_blank><font color=#808080>MailUp</font></a>
<a href="http://www.site.it/prodottiLLPP.php?id=1" class=""txtBlueGeorgia16"">Prodotti</a>
<a href="http://www.site.it/terremoto.php" target=""blank"" class=""txtGrigioScuroGeorgia12"">Terremoto</a>
<a class='mini' href='http://www.site.com/remove/professionisti.aspx?Id=65&Code=xhmyskwzse'>clicca qui.</a>`"""
>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup(html)
>>> [e['href'] for e in soup.findAll('a')]
[u'http://a0c5e.site.it/r', u'http://www.site.it/prodottiLLPP.php?id=1', u'http://www.site.it/terremoto.php', u'http://www.site.com/remove/professionisti.aspx?Id=65&Code=xhmyskwzse']

从乔恩克莱门茨

soup.findAll('a', {'href': True}) 

另一方面,您的 html 片段中的 href 引用不正确。

于 2012-12-16T17:51:30.900 回答
1

观察

Python 2.7.3 (default, Sep  4 2012, 20:19:03) 
[GCC 4.2.1 20070831 patched [FreeBSD]] on freebsd9
Type "help", "copyright", "credits" or "license" for more information.
>>> junk=''' <a href=""http://a0c5e.site.it/r"" target=_blank><font color=#808080>MailUp</font></a>
... <a href=""http://www.site.it/prodottiLLPP.php?id=1"" class=""txtBlueGeorgia16"">Prodotti</a>
... <a href=""http://www.site.it/terremoto.php"" target=""blank"" class=""txtGrigioScuroGeorgia12"">Terremoto</a>
... <a class='mini' href='http://www.site.com/remove/professionisti.aspx?Id=65&Code=xhmyskwzse'>clicca qui.</a>`'''
>>> import re
>>> pat=re.compile(r'''http[\:/a-zA-Z0-9\.\?\=&]*''')
>>> pat.findall(junk)
['http://a0c5e.site.it/r', 'http://www.site.it/prodottiLLPP.php?id=1', 'http://www.site.it/terremoto.php', 'http://www.site.com/remove/professionisti.aspx?Id=65&Code=xhmyskwzse']

可能想要添加 % 以便您可以捕获其他逃逸。

于 2012-12-16T17:54:18.353 回答
0

您可以使用BeautifulSoup 库来操作/提取 HTML 上的信息。

我不建议您使用正则表达式来解析 HTML 数据。HTML 不是规则的,它是上下文无关的语法。当链接结构发生变化时,HTML 可能有效,但您的正则表达式可能无效,您将不得不重新编写表达式。使用 BeautifulSoup 是一种提取信息的好方法。

于 2012-12-16T17:50:49.463 回答