gpt4 book ai didi

html - xpath 在页面中查找包含 HTML 的链接

转载 作者:行者123 更新时间:2023-12-03 17:32:59 25 4
gpt4 key购买 nike

这与 xpath find specific link in page 不是同一个问题。 .我有 <a href="http://example.com">foo <em class="bar">baz</em>.</a>.并且需要通过完整的foo <em class="bar">baz</em>.找到链接包括结束点。

最佳答案

注意:我正在跟进 OP 的评论

OP自己的答案的(视觉上)更简单的变体可能是:

//a[. = "foo baz."][em[@class = "bar"] = "baz"]

甚至:
//a[.="foo baz." and em[@class="bar"]="baz"]

(假设您要选择 <a> 节点,而不是子节点 <em> )

关于OP的问题:

why the [em[]= doesn't need the dot?



在谓词中,测试 =反对右边的字符串会将左边部分转换为字符串,这里是 <em>到它的字符串表示,即什么 string()会回来的。

XPath 1.0 规范文档有 an example of this :

chapter[title="Introduction"] selects the chapter children of the context node that have one or more title children with string-value equal to "Introduction"



后来, the same spec says在 bool 测试上:

If one object to be compared is a node-set and the other is a string, then the comparison will be true if and only if there is a node in the node-set such that the result of performing the comparison on the string-value of the node and the other string is true.



在 OP 的回答中, //a[string() = 'bar baz.']/em[@class='bar' and .='baz'] , .需要在 'baz' 上进行测试在上下文节点上

请注意,我的回答有点幼稚,并假设只有 1 <em> <a> 的 child , 因为 [em[@class="bar"]="baz"]正在寻找一个 em[@class="bar"]匹配字符串值条件,而不是它是唯一的或第一个。

考虑这个输入(第二个 <em class="bar"> child ,但为空):
<a href="http://example.com">foo <em class="bar">baz</em><em class="bar"></em>.</a>.

这个测试使用了 Scrapy 选择器
>>> import scrapy
>>> s = scrapy.Selector(text="""<a href="http://example.com">foo <em class="bar">baz</em><em class="bar"></em>.</a>.""")
>>> s.xpath('//a[.="foo baz." and em[@class="bar"]="baz"]').extract_first()
u'<a href="http://example.com">foo <em class="bar">baz</em><em class="bar"></em>.</a>'
>>>

XPath 匹配,但您可能不希望这样。

关于html - xpath 在页面中查找包含 HTML 的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31419933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com