脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python3爬虫爬取百姓网列表并保存为json功能示例【基于request、lxml和json模块】

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

2021-04-25 00:43包子源 Python

这篇文章主要介绍了Python3爬虫爬取百姓网列表并保存为json功能,涉及Python基于request、lxml和json模块的Request请求与响应数据处理相关操作技巧,需要的朋友可以参考下

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

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

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

首先需要安装requestslxmljson三个模块

需要手动创建d.json文件

代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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模块】

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

原文链接:https://blog.csdn.net/ziwoods/article/details/84257645

延伸 · 阅读

精彩推荐