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)

结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值