python3爬蟲之爬取百姓網列表並保存爲json

python3爬蟲之爬取百姓網列表並保存爲json文件。這幾天一直在學習使用python3爬取數據,今天記錄一下,代碼很簡單很容易上手。

首先需要安裝python3。如果還沒有安裝,請移步python3安裝與配置

首先需要安裝requests和lxml和json三個模塊

需要手動創建d.json文件

代碼

import requests
from lxml import etree
import 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")]')
# 存儲爲數組list
jsondata = []
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)
# 保存爲json
with open("./d.json",'w',encoding='utf-8') as json_file:
    json.dump(jsondata,json_file,ensure_ascii=False)

結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章