在元素和属性中搜索字符串

2024-10-03 13:23:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着查询一些HTML来找到包含“下载”这个词的链接。所以它可以在

  1. id
  2. class
  3. href
  4. 文本
  5. 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

Tags: textdividtreegetdownloadhtmlelements
2条回答

Xpathselect从严格匹配的a标记更改为通配符应该可以做到: "//*[(@id|@class|@href|text())[contains(translate(.,'DOWNLOAD','download'), 'download')]]"

纯XPath解决方案

text()更改为.,并在descendent-or-self轴上搜索属性:

//a[(.|.//@id|.//@class|.//@href)[contains(translate(.,'DOWNLOAD','download'),'download')]]

解释:

  • text()vs.:此处text()将匹配a的立即文本节点子级;.将匹配a元素的字符串值。在 以捕获存在a子元素的情况 包含目标文本时,要匹配 a。你知道吗
  • 后代或自身:为了匹配a及其任何后代的属性,使用descendant-or-self轴(.//)。你知道吗

有关XPath中字符串值的详细信息,请参见Matching text nodes is different than matching string values.

相关问题 更多 >