Python爬取數(shù)據(jù)保存為Json格式的代碼示例
更新時(shí)間:2019年04月09日 11:43:48 作者:zhanghl150426
今天小編就為大家分享一篇關(guān)于Python爬取數(shù)據(jù)保存為Json格式的代碼示例,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
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í)價(jià)值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
您可能感興趣的文章:
- Python eval函數(shù)的實(shí)現(xiàn)
- 基于Python爬取股票數(shù)據(jù)過程詳解
- Python爬取股票信息,并可視化數(shù)據(jù)的示例
- Python爬蟲實(shí)例——爬取美團(tuán)美食數(shù)據(jù)
- Python如何爬取實(shí)時(shí)變化的WebSocket數(shù)據(jù)的方法
- 實(shí)例講解Python爬取網(wǎng)頁數(shù)據(jù)
- Python3實(shí)現(xiàn)的爬蟲爬取數(shù)據(jù)并存入mysql數(shù)據(jù)庫操作示例
- python爬蟲爬取網(wǎng)頁表格數(shù)據(jù)
- Python手拉手教你爬取貝殼房源數(shù)據(jù)的實(shí)戰(zhàn)教程
相關(guān)文章
python中使用sys模板和logging模塊獲取行號和函數(shù)名的方法
這篇文章主要介紹了python中使用sys模板和logging模塊獲取行號和函數(shù)名的方法,需要的朋友可以參考下2014-04-04
Python生成任意波形并存為txt的實(shí)現(xiàn)
本文主要介紹了Python生成任意波形并存為txt的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11
python基于celery實(shí)現(xiàn)異步任務(wù)周期任務(wù)定時(shí)任務(wù)
這篇文章主要介紹了python基于celery實(shí)現(xiàn)異步任務(wù)周期任務(wù)定時(shí)任務(wù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12

