XPATH: 如果有一个元素具有特定值 "手机",则获取它的兄弟值

2024-04-19 16:16:09 发布

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

我有下列情况

...
...

<tr>
    <td class="company-info">Phone:</td>
    <td> "020 641512" <span class="provider">ABC</span></td>
</tr>
....

我想得到

  • 如果<td>具有值Phone:,则从下一个<td>获取电话号码(020 641512

我想象过这样的事情

phone = hxs.xpath("//td/text()[contains('Phone:')]", "Not available")

Tags: info情况phone电话号码provider事情trcompany
3条回答

使用scrapy SelectorSelectorList,您可以use regular expressions via their ^{} method

>>> hxs.xpath('//td[contains(., "Phone")]/following-sibling::td[1]').re(r'(\d[\d ]+\d)')
[u'020 641512']
>>> 

使用新的CSS选择器的替代方法:

>>> from scrapy.selector import Selector
>>> selector = Selector(response)
>>> selector.css('td:contains("Phone") + td').re(r'(\d[\d ]+\d)')
[u'020 641512']
>>> 

还有一个非常有用的Firefox插件,它可以帮助您理解名为Firebug的xpath,请看这些instructions。你知道吗

我想你需要:

//td[contains(., 'Phone:')]/following-sibling::td/substring-before(substring-after(normalize-space(text()[1]), '&quot;'), '&quot;')

上面的表达式在Xquery中工作,如果不工作,请尝试

//td[contains(., 'Phone:')]/following-sibling::td/text()[1]

它输出[space]"020 641512"

相关问题 更多 >