2016-01-05 108 views
0

我想从this page刮一些数据。正确的元素的Xpath

我在python中使用请求和lxml来做到这一点。 具体而言,我想要检测到的主题的ID。

我写了下面的XPath他们:

'//detectedTopic//@id' 

这回什么。

而下面的工作没有任何问题:

'//@id' 

在Chrome的开发者工具表明,第一个XPath确实指向正确的节点。

那么它有什么问题呢?

+0

can yo你尝试下面的两个例子? // detectedTopic/@id或 // detectedTopic –

回答

2

如果使用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将需要lowercased:

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

很好的回答!我不知道'lxml.html'使标记小写,因为我习惯使用'lxml.etree'来进行xml解析。 –

0

您可以通过此获得的ID:

'//detectedTopic/@id' 

您也可以获取代码和提取您需要的属性。例如:

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