正则表达式从HTML锚点中提取特定值

时间:2013-06-30 02:18:58

标签: python html regex

我正在尝试从下面的字符串中提取http://xyz.com/5链接。您可以看到,只有那个我们有class="next"属性。所以我试图基于这个属性得到它。

<a href='http://xyz.com/1' class='page larger'>2</a>
<a href='http://xyz.com/2' class='page larger'>3</a>
<a href='http://xyz.com/3' class='page larger'>4</a>
<a href='http://xyz.com/4' class='page larger'>5</a>
<a href='http://xyz.com/5' class="next">»</a>

我尝试了以下模式,但这会返回整个文本中的所有链接。

<a href='(.+?)' class="next">

(我从这个网站了解到使用正则表达式来解析HTML是一个坏主意,但我现在必须这样做。)

2 个答案:

答案 0 :(得分:2)

Please don't use regex to parse HTML。使用BeautifulSoup之类的内容。它更容易,更好:p

from bs4 import BeautifulSoup as BS
html = """<a href='http://xyz.com/1' class='page larger'>2</a>
<a href='http://xyz.com/2' class='page larger'>3</a>
<a href='http://xyz.com/3' class='page larger'>4</a>
<a href='http://xyz.com/4' class='page larger'>5</a>
<a href='http://xyz.com/5' class="next">»</a>"""
soup = BS(html)
for atag in soup.find_all('a', {'class':'next'}):
    print atag['href']

以您的示例打印:

http://xyz.com/5

此外,您的正则表达式works fine

答案 1 :(得分:2)

试试这个正则表达式:

<a href='([^']+)' class="next">

使正则表达式非贪婪并不意味着它总会找到最短的匹配。它只是意味着一旦找到匹配它将返回它,它将不会继续寻找更长的匹配。换句话说,它将使用通配符右侧的最短匹配,但不使用左侧。

因此,您的正则表达式在第一个链接的开头匹配,并一直持续到找到class = "next"。使用.+?而不是使用[^']+意味着通配符不会跨越属性边界,因此您可以确保只匹配一个链接。