xpath解析
- 編碼流程:
- 1.實例化一個etree對象,且將頁面源碼加載到該對象中
- 2.使用xpath函數,且在函數中必須作用一個xpath表達式進行標簽的定位
- 3.使用xpath進行屬性和文本的提取
- xpath表達式:
- / and //
- 索引和屬性定位://a[1] //a[@tagName]
- /text() //text()
- //a/@attrName
- xpath函數返回的一定是一個列表
- 環境安裝:
- pip install lxml
- 解析原理:
- 實例化一個etree的對象,且將頁面源碼數據加載到該對象中
- 調用etree對象中的xpath方法實現標簽定位和數據的提取
- 在xpath函數中必須作用xpath表達式
-
將 response.text 放到 etree.HTML( 中 ) 返回 tree 進行.xpath操作
-
取文本信息
- /text() 單層 //text() 多層
-
取屬性
- /@alt
- /@src
-
可使用:
-
tree.xpath('//div[@class="hot"]/div[@class="bottom"]/ul/li/a/text() | //div[@class="all"]/div[@class="bottom"]/ul/div[2]/li/a/text()') -
解析某二手房信息
import requests
from lxml import etree
headers = {
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'
}
url = 'https://bj.*****.com/shahe/ershoufang/pn1/'
page_text = requests.get(url=url,headers=headers).text
#數據解析(名稱,單價/總價,詳情)
tree = etree.HTML(page_text)
#li_list列表元素都是li標簽對象
li_list = tree.xpath('//ul[@class="house-list-wrap"]/li')
fp = open('./二手房.txt','w',encoding='utf-8')
for li in li_list:
title = li.xpath('./div[2]/h2/a/text()')[0]
detail = li.xpath('./div[2]/p//text()')
detail = ''.join(detail)
detail = detail.strip()
price = li.xpath('./div[3]/p//text()')
price = ''.join(price)
price = price.strip()
fp.write(title+':'+price+':'+detail+'\n')
fp.close()
print('over!!!')
