Python爬取数据保存为Json格式的代码示例
作者:zhanghl150426 时间:2022-10-13 17:11:36
python爬取数据保存为Json格式
代码如下:
#encoding:'utf-8'
import urllib.request
from bs4 import BeautifulSoup
import os
import time
import codecs
import json
#找到网址
def getDatas():
# 伪装
header={'User-Agent':"Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11"}
# url="https://movie.douban.com/top250"
url="file:///E:/scrapy/2018-04-27/movie/movie.html"
ret=urllib.request.Request(url=url,headers=header)
# 打开网页
res=urllib.request.urlopen(ret)
# 转化格式
response=BeautifulSoup(res,'html.parser')
# 找到想要数据的父元素
datas=response.find_all('div',{'class':'item'})
# print(datas)
#创建存放数据的文件夹
folder_name="output"
if not os.path.exists(folder_name):
os.mkdir(folder_name)
# 定义文件
current_time=time.strftime('%Y-%m-%d',time.localtime())
file_name="move"+current_time+".json"
# 文件路径
file_path=folder_name+"/"+file_name
for item in datas:
# print(item)
dict1={}
dict1['rank']=item.find('div',{'class':'pic'}).find('em').get_text()
dict1['title']=item.find('div',{'class':'info'}).find('div',{'class':'hd'}).find('a').find('span',{'class':'title'}).get_text()
dict1['picUrl']=item.find('div',{'class':'pic'}).find('a').find('img').get('src')
# print(picUrl)
# 保存数据为json格式
try:
with codecs.open(file_path,'a',encoding="utf-8") as fp:
fp.write(json.dumps(dict1,ensure_ascii=False)+",\n")
except IOError as err:
print('error'+str(err))
finally:
fp.close()
pass
getDatas()
# 爬取数据
来源:https://blog.csdn.net/zhanghl150426/article/details/82022339
标签:python,爬取数据,json格式
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
javascript新闻图片轮换类
2009-01-09 12:57:00
闲聊html和body标签
2009-02-21 10:50:00
Asp教程:Response对象
2007-10-01 18:08:00
Django应用程序入口WSGIHandler源码解析
2021-07-09 04:33:22
Div即父容器不根据内容自适应高度的解决方法
2010-04-23 18:19:00
教你如何将 Sublime 3 打造成 Python/Django IDE开发利器
2022-10-10 11:37:29
![](https://img.aspxhome.com/file/2023/7/63887_0s.png)
MSSQL数据类型
2008-08-03 17:21:00
python使用pandas读xlsx文件的实现
2021-01-21 05:00:10
![](https://img.aspxhome.com/file/2023/9/79669_0s.jpg)
Google中秋logo被恶搞
2007-09-25 15:55:00
python+opencv识别图片中的圆形
2022-02-10 00:04:23
![](https://img.aspxhome.com/file/2023/5/92355_0s.jpg)
基于Python和Scikit-Learn的机器学习探索
2023-12-25 00:41:10
C#调用Python模块的方法
2021-04-13 15:29:10
![](https://img.aspxhome.com/file/2023/9/71749_0s.png)
基于tensorflow指定GPU运行及GPU资源分配的几种方式小结
2021-10-03 10:22:27
![](https://img.aspxhome.com/file/2023/1/81731_0s.jpg)
Go语言流程控制详情
2023-10-16 13:16:24
Asp用分页符实现长文章分页
2007-10-19 18:35:00
Python中FTP服务与SSH登录暴力破解的实现
2022-12-14 13:25:43
![](https://img.aspxhome.com/file/2023/4/75204_0s.png)
5.PHP的其他功能
2023-11-14 16:45:42
python字典的遍历3种方法详解
2022-05-01 06:00:44
![](https://img.aspxhome.com/file/2023/6/79646_0s.png)
深入理解Python中变量赋值的问题
2023-03-20 00:28:07
别人复制你网站的文章时自动加上注释
2009-02-09 13:20:00