python爬蟲三大解析資料方法:xpath 及 爬段子網案例
阿新 • • 發佈:2018-12-21
下載
pip install lxml
瀏覽器外掛
外掛xpath安裝,XPath Helper 瀏覽器快捷鍵control+shift+x 用於測試自己的xpath是否寫對了
注意
etree建立物件時 etree.parse('本地路徑') 或 etree.HTML('網上請求到的頁面')
常用方法
返回值都是列表
from lxml import etree
etree = etree.parse('./測試.html')
# 屬性定位
# 找class屬性值為song的標籤
etree.xpath('//div[@class="song"]')
# 層級索引定位 class下的ul下的第二個li中的a標籤
etree.xpath('//div[@class="song"]/ul/li[2]/a')
# 邏輯定位 找到所有a標籤, href屬性為'' 而且 class為song的
etree.xpath('//a[@href="" and @class="song"]')
# 模糊匹配
# 所有div標籤,中class包含ng這兩個字眼的所有標籤
etree.xpath('//div[contains(@class, "ng")]')
# 所有div下, 以ta開頭的 class
etree.xpath('//div[starts-with(@class, "ta")]')
# 取文字
# 精準定位後text()取文字
etree.xpath('//div[@class="song"]/p[1]/text()')
# 將制定到位置,下所有子標籤的文字獲取到 //text()
etree.xpath('//div[@class="song"]//text()')
# 取屬性 @屬性名
etree.xpath('//div[@class="song"]//li[2]/a/@href')
段子網內容和標題解析
import requests
from lxml import etree
url = 'https://ishuo.cn/'
headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36' ,
}
data = requests.get(url, headers=headers).text
etree = etree.HTML(data)
# 取到包含內容和標題 Element物件可以繼續用xpath繼續呼叫
with open('./段子內容.txt', 'w', encoding='utf-8') as f:
li_list = etree.xpath('//div[@id="list"]/ul/li')
for li in li_list:
# ./代表從li開始取
title = li.xpath('./div[2]/a/text()')[0]
content = li.xpath('./div[1]/text()')[0]
f.write("【"+title+"】"+content+"\n\n")
print('資料寫入完成')