Python爬取數(shù)據(jù)保存為Json格式的代碼示例
更新時(shí)間:2019年04月09日 11:43:48 作者:zhanghl150426
今天小編就為大家分享一篇關(guān)于Python爬取數(shù)據(jù)保存為Json格式的代碼示例,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
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) # 打開(kāi)網(wǎng)頁(yè) 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é)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
您可能感興趣的文章:
- python實(shí)現(xiàn)模擬器爬取抖音評(píng)論數(shù)據(jù)的示例代碼
- 基于Python爬取股票數(shù)據(jù)過(guò)程詳解
- Python爬取股票信息,并可視化數(shù)據(jù)的示例
- Python爬蟲(chóng)實(shí)例——爬取美團(tuán)美食數(shù)據(jù)
- Python如何爬取實(shí)時(shí)變化的WebSocket數(shù)據(jù)的方法
- 實(shí)例講解Python爬取網(wǎng)頁(yè)數(shù)據(jù)
- Python3實(shí)現(xiàn)的爬蟲(chóng)爬取數(shù)據(jù)并存入mysql數(shù)據(jù)庫(kù)操作示例
- python爬蟲(chóng)爬取網(wǎng)頁(yè)表格數(shù)據(jù)
- Python手拉手教你爬取貝殼房源數(shù)據(jù)的實(shí)戰(zhàn)教程
相關(guān)文章
使用Python對(duì)文件進(jìn)行批量改名的方法
這篇文章主要介紹了使用Python對(duì)文件進(jìn)行批量改名的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-03-03Python在畫(huà)圖時(shí)使用特殊符號(hào)的方法總結(jié)
在制作圖表時(shí),如果遇到需要利用特殊符號(hào)進(jìn)行表示時(shí)該怎么辦呢?不用慌,這篇文章為大家總結(jié)了python畫(huà)圖中使用各種特殊符號(hào)的方式,需要的可以參考一下2022-04-04python編輯用戶登入界面的實(shí)現(xiàn)代碼
這篇文章主要介紹了python編輯用戶登入界面的實(shí)現(xiàn)代碼,非常不錯(cuò),代碼簡(jiǎn)單易懂,具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-07-07python計(jì)算波峰波谷值的方法(極值點(diǎn))
這篇文章主要介紹了python求極值點(diǎn)(波峰波谷)求極值點(diǎn)主要用到了scipy庫(kù),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02