我试着查询一些HTML来找到包含“下载”这个词的链接。所以它可以在
id
class
href
a
标记中的任何html。你知道吗因此,使用Python lxml library应该可以找到测试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只能在文本中找到“download”。你知道吗
有没有办法把a
标记的内容看作一个常规字符串,看看它是否包含“download”?欢迎所有提示!你知道吗
[编辑]
使用下面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
将
Xpath
select从严格匹配的a
标记更改为通配符应该可以做到:"//*[(@id|@class|@href|text())[contains(translate(.,'DOWNLOAD','download'), 'download')]]"
纯XPath解决方案
将
text()
更改为.
,并在descendent-or-self
轴上搜索属性:解释:
text()
vs.
:此处text()
将匹配a
的立即文本节点子级;.
将匹配a
元素的字符串值。在 以捕获存在a
子元素的情况 包含目标文本时,要匹配a
。你知道吗a
及其任何后代的属性,使用descendant-or-self
轴(.//
)。你知道吗有关XPath中字符串值的详细信息,请参见Matching text nodes is different than matching string values.
相关问题 更多 >
编程相关推荐