gpt4 book ai didi

html - XPath 根据兄弟/表亲文本选择元素?

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

我正在尝试获取 Chief Executive 的联系方式和 Someone Else
我可以使用以下代码找到首席执行官

response.xpath('*/div[@class="outer"]/h2/text()="Chief Executive"')

# Returns a Selector
[<Selector xpath='*/div[@class="outer"]/h2/text()="Chief Executive"' data=u'0'>]

但是,一旦我尝试访问 parent 或 sibling ,我要么得到错误,要么没有数据。

这是我尝试过的一些模式

1.
response.xpath('*/div[@class="outer"]/h2/text()="Chief Executive"/following-sibling')

ValueError: XPath error: Invalid type in */div[@class="outer"]/h2/text()="Chief Executive"/following-sibling

2.
response.xpath('*/div[@class="outer"]/h2/text()="Chief Executive"/following-sibling::content')

ValueError: XPath error: Invalid type in */div[@class="outer"]/h2/text()="Chief Executive"/following-sibling::content

3.
response.xpath('*/div[@class="outer"]/h2/text()="Chief Executive"/parent::*')

ValueError: XPath error: Invalid type in */div[@class="outer"]/h2/text()="Chief Executive"/parent::*

4
response.xpath('*/div[@class="outer"]/h2/text()="Chief Executive"/..')

ValueError: XPath error: Invalid type in */div[@class="outer"]/h2/text()="Chief Executive"/..

5
response.xpath('*/div[@class="outer"]/h2[.="Chief Executive"]')

[] # No data found

6
response.xpath('*/div[@class="outer"]/h2[text()="Chief Executive"]')

[] # No data found

基础 HTML
<div class="outer">
<h2 class="legend">
Chief Executive
</h2>

<div class="fieldset">

<div class="display-row">
<div class="display-label">Contact name:</div>
<div class="display-field-no-width">
Mr. Steven Bob
</div>
</div>

<div class="display-row">
<div class="display-label">Job title:</div>
<div class="display-field-no-width">
Chief Executive Officer
</div>
</div>

<div class="display-row">
<div class="display-label">Organisation name:</div>
<div class="display-field-no-width">
1 COMAPNY PTY LTD
</div>
</div>

</div>
</div>


<div class="outer">
<h2 class="legend">
Someone Else
</h2>

<div class="fieldset">

<div class="display-row">
<div class="display-label">Contact name:</div>
<div class="display-field-no-width">
Mr. Steven Bob
</div>
</div>

<div class="display-row">
<div class="display-label">Job title:</div>
<div class="display-field-no-width">
Chief Executive Officer
</div>
</div>

<div class="display-row">
<div class="display-label">Organisation name:</div>
<div class="display-field-no-width">
1 COMAPNY PTY LTD
</div>
</div>

</div>
</div>

最佳答案

这个 XPath,

normalize-space(//div[normalize-space(h2)='Chief Executive']
/div[div[1]='Contact name:'])

将返回
Mr. Steven Bob

按照此模式,您可以从此条目或 Someone Else 的条目中选择其他字段。 , 按照要求。

关于html - XPath 根据兄弟/表亲文本选择元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47877859/

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