更正元素的 Xpath

Correct Xpath for element

我正在尝试从 this page 抓取一些数据。

我在 python 中使用请求和 lxml 来执行此操作。 具体来说,我想要检测到的主题的 ID。

我为他们编写了以下 Xpath :

'//detectedTopic//@id'

这没有返回任何内容。

而以下操作没有任何问题:

'//@id'

Chrome 中的开发人员工具显示第一个 Xpath 确实指向正确的节点。

那到底是怎么回事?

您可以通过以下方式获取ID:

'//detectedTopic/@id'

您还可以获取标签并提取所需的属性。示例:

for tag in tr.xpath('//detectedTopic'):
    print tag.attrib.get('id')
    print tag.attrib.get('title')

如果您使用 lxml.html 来解析内容,那么 HTMLParser 会使所有标签变为小写,因为 HTML is case-insensitive:

import requests
url = 'http://wikipedia-miner.cms.waikato.ac.nz/services/wikify?source=At%20around%20the%20size%20of%20a%20domestic%20chicken,%20kiwi%20are%20by%20far%20the%20smallest%20living%20ratites%20and%20lay%20the%20largest%20egg%20in%20relation%20to%20their%20body%20size%20of%20any%20species%20of%20bird%20in%20the%20world'
r = requests.get(url)
content = r.content

import lxml.html as LH
html_root = LH.fromstring(content)
print(LH.tostring(html_root))

产量

...
   <detectedtopics>
      <detectedtopic id="17362" title="Kiwi" weight="0.8601778098224363"></detectedtopic>
      <detectedtopic id="21780446" title="Species" weight="0.6213590253455182"></detectedtopic>
      <detectedtopic id="160220" title="Ratite" weight="0.5533763404831633"></detectedtopic>
      <detectedtopic id="37402" title="Chicken" weight="0.528161911497278"></detectedtopic>
   </detectedtopics>

但是如果使用lxml.etree解析内容为XML,则大小写不变:

import lxml.etree as ET
xml_root = ET.fromstring(content)
print(ET.tostring(xml_root))

产量

...
   <detectedTopics>
      <detectedTopic id="17362" title="Kiwi" weight="0.8601778098224363"/>
      <detectedTopic id="21780446" title="Species" weight="0.6213590253455182"/>
      <detectedTopic id="160220" title="Ratite" weight="0.5533763404831633"/>
      <detectedTopic id="37402" title="Chicken" weight="0.528161911497278"/>
   </detectedTopics>

内容看起来像 XML 而不是 HTML,所以你应该使用:

print(xml_root.xpath('//detectedTopic/@id'))
['17362', '21780446', '160220', '37402']

如果内容被解析为 HTML,则 XPath 需要小写:

print(html_root.xpath('//detectedtopic/@id'))
['17362', '21780446', '160220', '37402']