新手Python/正则:使用正则提取<a>标签中的字符串

1 投票
6 回答
2317 浏览
提问于 2025-04-17 09:04

我需要在Python中使用re模块提取href属性标签之间的字符串。

我尝试了很多不同的匹配模式,比如:

patFinderLink = re.compile('\>"(CVE.*)"\<\/a>')

举个例子:我想从以下内容中提取标签之间的内容(在这个例子中是"CVE-2010-3718"):

<pre>
<a href="https://www.redhat.com/security/data/cve/CVE-2010-3718.html">CVE-2010-3718</a>
</pre>

我在这里做错了什么呢?任何建议都非常感谢。提前谢谢你们。

Sun

6 个回答

2

不要试图用正则表达式来解析HTML或XML。应该使用像lxml这样的解析器。

import lxml.html as lh

tree = lh.fromstring(html)

print tree.xpath("//pre/a[starts-with(., 'CVE')]/text()")

结果:

['CVE-2010-3718']
6

你真的需要用正则表达式吗?我觉得不需要,因为用正则表达式无法解析SGML,因为SGML本身并不是规则的。想了解更多,可以看看这个著名的StackOverflow回答:https://stackoverflow.com/a/1732454/88123

不过,建议你使用Python的lxml模块以及它的xpath功能。xpath可以帮助你选择以特定文本开头的内容。

在这种情况下,XPath的写法是//h1/text()

另外,你也可以使用Python的BeautifulSoup模块。

0

我很惊讶居然没有人建议使用BeautifulSoup这个工具:

这是我会做的方式:

from BeautifulSoup import BeautifulSoup
import re

hello = """
<pre>
<a href="https://www.redhat.com/security/data/cve/CVE-2010-3718.html">CVE-2010-3718</a>
<a href="https://www.redhat.com/security/data/cve/CVE-2010-3710.html">CVE-2010-3718</a>
<a href="https://www.redhat.com/security/data/cve/CVE-2010-3700.html">CVE-2010-3718</a>
</pre>
"""

target = re.compile("CVE-\d+-\d+.html")
commentSoup = BeautifulSoup(hello)
atags = commentSoup.findAll(href=target)
for a in atags:
    match = re.findall(target, a['href'])[0]
    print match

结果:

CVE-2010-3718.html
CVE-2010-3710.html
CVE-2010-3700.html

撰写回答