2017-05-07 92 views
1

我正在進行第二套住房定價項目,所以我需要從中國最大的第二家交易平臺之一中獲取信息。這裏是我的問題,是頁面上的信息,並使用Chrome「檢查」功能,相應的元素如下:無法使用lxml和xpath從html中檢索文本

enter image description here

我的代碼:

>>>from lxml import etree 
>>>import requests 
>>>url = 'http://bj.lianjia.com/chengjiao/101101498110.html' 
>>>r = requests.get(url) 
>>>xiaoqu_avg_price = tree.xpath('//[@id="resblockCardContainer"]/div/div/div[2]/div/div[1]/span/text()') 
>>>xiaoqu_avg_price 
[] 

返回空列表是不可取的(理想情況下它應該是73648)。此外,我認爲它的HTML源代碼,其中顯示:

enter image description here

那麼應該怎麼辦得到我想要什麼?什麼是resblockCard的意思?謝謝。

+0

你試過用'.xiaoqu_main_info/text()' –

回答

1

這個網站和許多其他人一樣使用ajax來填充內容。如果您提出類似的請求,您可以使用json格式獲得所需的值。

import requests 

url = 'http://bj.lianjia.com/chengjiao/resblock?hid=101101498110&rid=1111027378082' 
# Get json response 
response = requests.get(url).json() 
print(response['data']['resblock']['unitPrice']) 
# 73648 

請注意請求url中的兩組數字。 resblockId:'1111027378082':從原來的頁面URL中的第一組,第二你可以在script標籤在原頁面的源代碼發現。

0

這是預期的,因爲你正在運行它靠在頁面的源代碼,因爲它是由服務器提供的,並不像它看起來呈現的瀏覽器頁面上的XPath查詢不工作。

對此的一個解決方案是使用SeleniumPhantomJS或其他瀏覽器驅動程序一起使用,該驅動程序將在該頁面上運行JavaScript並呈現給您。

from selenium import webdriver 
from lxml import html 

driver = webdriver.PhantomJS(executable_path="<path to>/phantomjs.exe") 
driver.get('http://bj.lianjia.com/chengjiao/101101498110.html') 
source = driver.page_source 
driver.close() # or quit() if there are no more pages to scrape 

tree = html.fromstring(source) 
price = tree.xpath('//div[@id="resblockCardContainer"]/div/div/div[2]/div/div[1]/span/text()')[0].strip() 

以上返回73648 元/㎡