作者前言
?歡迎小可愛們前來借鑒我的gtiee秦老大大 (qin-laoda) - Gitee.com
目錄
為什么要學(xué)習(xí)XPATH和LXML類庫(kù)
什么是XPATH
認(rèn)識(shí)XML
?XML的節(jié)點(diǎn)關(guān)系

節(jié)點(diǎn)選擇語法
?節(jié)點(diǎn)修飾語法

?lxml庫(kù)

?下面我來爬取一個(gè)頁(yè)面來給小可愛們
代碼:
import requests
from lxml import etree
def parse_data(html):
# 創(chuàng)建一個(gè)xpath對(duì)象
e_html=etree.HTML(html)
# print(e_html.xpath('//main[@id="c-626160000"]'))
for i in e_html.xpath('//main[@id="c-626160000"]'):
print("/n".join(i.xpath('./p//text()')).strip())
return "".join(i.xpath('./p//text()')).strip()
def save_data(data):
with open("小說.txt","w",encoding="utf-8")as f:
f.write(data)
def parse_url(url,header):
response = requests.get(url)
return response
def main():
"""主要的業(yè)務(wù)邏輯"""
# url
url = "https://www.qidian.com/chapter/1021617576/626160000/"
header = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}
# 發(fā)送請(qǐng)求獲取響應(yīng)
response = parse_url(url, header)
# print(response.text)
html = response.text
# 數(shù)據(jù)的提取
data = parse_data(html)
# 保存
save_data(data)
if __name__ == '__main__':
main()
結(jié)果:
文章來源:http://www.zghlxwxcb.cn/news/detail-492532.html
?總結(jié)
這里我簡(jiǎn)單的介紹了xpath的使用和語法,小可愛有哪些不明白的可以私聊了文章來源地址http://www.zghlxwxcb.cn/news/detail-492532.html
到了這里,關(guān)于python---------xpath提取數(shù)據(jù)------打破局限的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!