【发布时间】:2016-01-05 14:13:51
【问题描述】:
我正在尝试查询一些 HTML 以查找以某种方式包含“下载”一词的链接。所以它可以在
-
id -
class -
href - 正文
-
a标记内的任何 html。
所以使用Python lxml library 应该会在 test-html 中找到所有 7 个链接:
html = """
<html>
<head></head>
<body>
1 <a href="/test1" id="download">test 1</a>
2 <a href="/test2" class="download">test 2</a>
3 <a href="/download">test 3</a>
4 <a href="/test4">DoWnLoAd</a>
5 <a href="/test5">ascascDoWnLoAdsacsa</a>
6 <a href="/test6"><div id="test6">download</div></a>
7 <a href="/test7"><div id="download">test7</div></a>
</body>
</html>
"""
from lxml import etree
tree = etree.fromstring(html, etree.HTMLParser())
downloadElementConditions = "//a[(@id|@class|@href|text())[contains(translate(.,'DOWNLOAD','download'), 'download')]]"
elements = tree.xpath(downloadElementConditions)
print 'FOUND ELEMENTS:', len(elements)
for i in elements:
print i.get('href'), i.text
但是,如果运行它,它只会找到前五个元素。这意味着如果文本不包含进一步的 html,xpath 只能在文本中找到“下载”。
有没有办法将a 标记的内容视为常规字符串并查看其中是否包含“下载”?欢迎所有提示!
[编辑]
使用下面 heinst 答案中的提示,我编辑了下面的代码。这现在有效,但它不是很优雅。有人知道纯 xpath 的解决方案吗?
from lxml import etree
tree = etree.fromstring(html, etree.HTMLParser())
downloadElementConditions = "//*[(@id|@class|@href|text())[contains(translate(.,'DOWNLOAD','download'), 'download')]]"
elements = tree.xpath(downloadElementConditions)
print 'FOUND ELEMENTS:', len(elements)
for el in elements:
href = el.get('href')
if href:
print el.get('href'), el.text
else:
elparent = el
for _ in range(10): # loop over 10 parents
elparent = elparent.getparent()
href = elparent.get('href')
if href:
print elparent.get('href'), elparent.text
break
【问题讨论】:
标签: python html xml xpath lxml