Python爬取數(shù)據(jù)保存為Json格式的代碼示例
更新時間:2019年04月09日 11:43:48 作者:zhanghl150426
今天小編就為大家分享一篇關(guān)于Python爬取數(shù)據(jù)保存為Json格式的代碼示例,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
python爬取數(shù)據(jù)保存為Json格式
代碼如下:
#encoding:'utf-8'
import urllib.request
from bs4 import BeautifulSoup
import os
import time
import codecs
import json
#找到網(wǎng)址
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)
# 打開網(wǎng)頁
res=urllib.request.urlopen(ret)
# 轉(zhuǎn)化格式
response=BeautifulSoup(res,'html.parser')
# 找到想要數(shù)據(jù)的父元素
datas=response.find_all('div',{'class':'item'})
# print(datas)
#創(chuàng)建存放數(shù)據(jù)的文件夾
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)
# 保存數(shù)據(jù)為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()
# 爬取數(shù)據(jù)
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
您可能感興趣的文章:
- python實現(xiàn)模擬器爬取抖音評論數(shù)據(jù)的示例代碼
- 基于Python爬取股票數(shù)據(jù)過程詳解
- Python爬取股票信息,并可視化數(shù)據(jù)的示例
- Python爬蟲實例——爬取美團(tuán)美食數(shù)據(jù)
- Python如何爬取實時變化的WebSocket數(shù)據(jù)的方法
- 實例講解Python爬取網(wǎng)頁數(shù)據(jù)
- Python3實現(xiàn)的爬蟲爬取數(shù)據(jù)并存入mysql數(shù)據(jù)庫操作示例
- python爬蟲爬取網(wǎng)頁表格數(shù)據(jù)
- Python手拉手教你爬取貝殼房源數(shù)據(jù)的實戰(zhàn)教程

