本文實例講述了Python3爬蟲爬取百姓網列表并保存為json功能。分享給大家供大家參考,具體如下:
python3爬蟲之爬取百姓網列表并保存為json文件。這幾天一直在學習使用python3爬取數據,今天記錄一下,代碼很簡單很容易上手。
首先需要安裝python3。如果還沒有安裝,可參考本站python3安裝與配置相關文章。
首先需要安裝requests和lxml和json三個模塊
需要手動創建d.json文件
代碼
import requestsfrom lxml import etreeimport json#構造頭文件,模擬瀏覽器訪問url="http://xian.baixing.com/meirongfuwu/"headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36','referer':url}response=requests.get(url,headers=headers)body=response.text #獲取網頁內容html=etree.HTML(body,etree.HTMLParser())gethtml=html.xpath('//div[contains(@class,"media-body-title")]')# 存儲為數組listjsondata = []for item in gethtml: jsonone={} jsonone['title']=item.xpath('.//a[contains(@class,"ad-title")]/text()')[0] jsonone['url']=item.xpath('.//a[contains(@class,"ad-title")]/attribute::href')[0] jsonone['phone']=item.xpath('.//button[contains(@class,"contact-button")]/attribute::data-contact')[0] jsondata.append(jsonone)# 保存為jsonwith open("./d.json",'w',encoding='utf-8') as json_file: json.dump(jsondata,json_file,ensure_ascii=False)結果
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答