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實(shí)現(xiàn)模擬器爬取抖音評論數(shù)據(jù)的示例代碼
- 基于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在畫圖時(shí)使用特殊符號的方法總結(jié)
在制作圖表時(shí),如果遇到需要利用特殊符號進(jìn)行表示時(shí)該怎么辦呢?不用慌,這篇文章為大家總結(jié)了python畫圖中使用各種特殊符號的方式,需要的可以參考一下2022-04-04python編輯用戶登入界面的實(shí)現(xiàn)代碼
這篇文章主要介紹了python編輯用戶登入界面的實(shí)現(xiàn)代碼,非常不錯(cuò),代碼簡單易懂,具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-07-07python計(jì)算波峰波谷值的方法(極值點(diǎn))
這篇文章主要介紹了python求極值點(diǎn)(波峰波谷)求極值點(diǎn)主要用到了scipy庫,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02