欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python3爬虫爬取百姓网列表并保存为json功能示例【基于request、lxml和json模块】

程序员文章站 2022-04-17 11:01:32
本文实例讲述了python3爬虫爬取百姓网列表并保存为json功能。分享给大家供大家参考,具体如下: python3爬虫之爬取百姓网列表并保存为json文件。这几天一直在...

本文实例讲述了python3爬虫爬取百姓网列表并保存为json功能。分享给大家供大家参考,具体如下:

python3爬虫之爬取百姓网列表并保存为json文件。这几天一直在学习使用python3爬取数据,今天记录一下,代码很简单很容易上手。

首先需要安装python3。如果还没有安装,可参考本站python3安装与配置相关文章。

首先需要安装requestslxmljson三个模块

需要手动创建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)

结果

Python3爬虫爬取百姓网列表并保存为json功能示例【基于request、lxml和json模块】

ps:这里再为大家推荐几款比较实用的json在线工具供大家参考使用:

在线json代码检验、检验、美化、格式化工具:

json在线格式化工具:

在线xml/json互相转换工具:

json代码在线格式化/美化/压缩/编辑/转换工具:

在线json压缩/转义工具:

更多关于python相关内容可查看本站专题:《python socket编程技巧总结》、《python正则表达式用法总结》、《python数据结构与算法教程》、《python函数使用技巧总结》、《python字符串操作技巧汇总》、《python入门与进阶经典教程》及《python文件与目录操作技巧汇总

希望本文所述对大家python程序设计有所帮助。