簡體   English   中英

元素的正確Xpath

[英]Correct Xpath for element

我正在嘗試從此頁面抓取一些數據。

我在python中使用請求和lxml。 具體來說,我想要檢測到的主題的ID。

我為他們編寫了以下Xpath:

'//detectedTopic//@id'

這什么也沒返回。

鑒於以下工作沒有任何問題:

'//@id'

Chrome中的開發人員工具顯示,第一個Xpath確實指向正確的節點。

那怎么了

如果使用lxml.html來解析內容,則HTMLParser lxml.html所有標簽都小寫,因為HTML不區分大小寫

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']

您可以通過以下方式獲取ID:

'//detectedTopic/@id'

您也可以獲取標簽並提取所需的屬性。 例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM