繁体   English   中英

在Python中使用Regex匹配大于HTML字符

[英]Matching greater than HTML character with Regex in Python

我正在尝试使用re.compile来匹配网页上的值

我的网页包含以下HTML:

<div id="paginate">
&nbsp;<strong>1</strong>
&nbsp;<a href="http://www.link2.com/">2</a>
&nbsp;<a href="http://www.link3.com/">3</a>
&nbsp;<a href="http://www.link2.com">&gt;</a>
&nbsp;&nbsp;<a href="http://www.link20.com/">Last &rsaquo;</a>
</div>

我的正则表达式如下:

re.compile('<a href="(.+?)">&gt;</a>').findall()

这返回

['http://www.link2.com/">2</a>
&nbsp;<a href="http://www.link3.com">3</a>
&nbsp;<a href="http://www.link2.com/']

我只想获取包含大于符号作为其标签的链接的href?

有任何想法吗?

提前致谢

只需使用re.findall()

>>> re.findall('<a href="(.+?)">&gt;</a>', html)
['http://www.link4.com']

请注意,您实际上应该使用HTML解析器而不是regex解析HTML。 我建议BeautifulSoup

>>> from bs4 import BeautifulSoup as BS
>>> soup = BS(html)
>>> print soup.find('a', text='>')
<a href="http://www.link4.com">&gt;</a>
>>> print soup.find('a', text='>')['href']
http://www.link4.com

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM