我正在尝试使用lxml来获取格式为的注释数组
<div id="comment-1">
TEXT
</div>
<div id="comment-2">
TEXT
</div>
<div id="comment-3">
TEXT
</div>
...
我试过用
html.findall(".//div[@id='comment-*']")
但是这会搜索文字星号.
我正在尝试做什么是正确的语法?
编辑:我终于通过这样做了
doc = lxml.html.parse(url).getroot()
comment_array = doc.xpath('.//div[starts-with(@id, "comment-")]')
解决方法:
您可以使用regular XPath functions查找建议的注释:
comments = doc.xpath('.//div[starts-with(@id, "comment-")]')
但是,对于更复杂的匹配,您可以使用正则表达式:对于lxml,XPath支持EXSLT命名空间中的正则表达式.参见官方文档Regular expressions in XPath.
这是一个演示:
from lxml import etree
content = """\
<body>
<div id="comment-1">
TEXT
</div>
<div id="comment-2">
TEXT
</div>
<div id="comment-3">
TEXT
</div>
<div id="note-4">
not matched
</div>
</body>
"""
doc = etree.XML(content)
# You must give the namespace to use EXSLT RegEx
REGEX_NS = "http://exslt.org/regular-expressions"
comments = doc.xpath(r'.//div[re:test(@id, "^comment-\d+$")]',
namespaces={'re': REGEX_NS})
要查看结果,您可以“转储”匹配的节点:
for comment in comments:
print("---")
etree.dump(comment)
你得到:
---
<div id="comment-1">
TEXT
</div>
---
<div id="comment-2">
TEXT
</div>
---
<div id="comment-3">
TEXT
</div>