Python爬取豆瓣數(shù)據(jù)實(shí)現(xiàn)過(guò)程解析
代碼如下
from bs4 import BeautifulSoup #網(wǎng)頁(yè)解析,獲取數(shù)據(jù) import sys #正則表達(dá)式,進(jìn)行文字匹配 import re import urllib.request,urllib.error #指定url,獲取網(wǎng)頁(yè)數(shù)據(jù) import xlwt #使用表格 import sqlite3 import lxml
以上是引用的庫(kù),引用庫(kù)的方法很簡(jiǎn)單,直接上圖:
上面第一步算有了,下面分模塊來(lái),步驟算第二步來(lái):
這個(gè)放在開(kāi)頭
def main(): baseurl ="https://movie.douban.com/top250?start=" datalist = getData(baseurl) savepath=('douban.xls') saveData(datalist,savepath)
這個(gè)放在末尾
if __name__ == '__main__':
main()
不難看出這是主函數(shù),里面的話(huà)是對(duì)子函數(shù)的調(diào)用,下面是第三個(gè)步驟:子函數(shù)的代碼
對(duì)網(wǎng)頁(yè)正則表達(dá)提取(放在主函數(shù)的后面就可以)
findLink = re.compile(r'<a href="(.*?)" rel="external nofollow" rel="external nofollow" >') #創(chuàng)建正則表達(dá)式對(duì)象,表示規(guī)則(字符串的模式)
#影片圖片
findImg = re.compile(r'<img.*src="(.*?)" width="100"/>',re.S)#re.S取消換行符
#影片片面
findtitle= re.compile(r'<span class="title">(.*?)</span>')
#影片評(píng)分
fileRating = re.compile(r'<span class="rating_num" property="v:average">(.*?)</span>')
#找到評(píng)價(jià)的人數(shù)
findJudge = re.compile(r'<span>(\d*)人評(píng)價(jià)</span>')
#找到概識(shí)
findInq =re.compile(r'<span class="inq">(.*?)</span>')
#找到影片的相關(guān)內(nèi)容
findBd = re.compile(r'<p class="">(.*?)</p>',re.S)
爬數(shù)據(jù)核心函數(shù)
def getData(baseurl): datalist=[] for i in range(0,10):#調(diào)用獲取頁(yè)面的函數(shù)10次 url = baseurl + str(i*25) html = askURl(url) #逐一解析 soup = BeautifulSoup(html,"html.parser") for item in soup.find_all('div',class_="item"): #print(item) data=[] item = str(item) link = re.findall(findLink,item)[0] #re庫(kù)用來(lái)通過(guò)正則表達(dá)式查找指定的字符串 data.append(link) titles =re.findall(findtitle,item) if(len(titles)==2): ctitle=titles[0].replace('\xa0',"") data.append(ctitle)#添加中文名 otitle = titles[1].replace("\xa0/\xa0Perfume:","") data.append(otitle)#添加外國(guó)名 else: data.append(titles[0]) data.append(' ')#外國(guó)名字留空 imgSrc = re.findall(findImg,item)[0] data.append(imgSrc) rating=re.findall(fileRating,item)[0] data.append(rating) judgenum = re.findall(findJudge,item)[0] data.append(judgenum) inq=re.findall(findInq,item) if len(inq) != 0: inq =inq[0].replace(".","") data.append(inq) else: data.append(" ") bd=re.findall(findBd,item)[0] bd=re.sub('<br(\s+)?/>(\s+)?'," ",bd) #去掉<br/> bd =re.sub('\xa0'," ",bd) data.append(bd.strip()) #去掉前后的空格 datalist.append(data) #把處理好的一部電影信息放入datalist return datalist
獲取指定網(wǎng)頁(yè)內(nèi)容
def askURl(url): head = { "User-Agent": "Mozilla / 5.0(Windows NT 10.0;WOW64) Apple" +"WebKit / 537.36(KHTML, likeGecko) Chrome / 78.0.3904.108 Safari / 537.36" } #告訴豆瓣我們是瀏覽器我們可以接受什么水平的內(nèi)容 request = urllib.request.Request(url,headers=head) html="" try: response = urllib.request.urlopen(request) html = response.read().decode("utf-8") # print(html) except urllib.error.URLError as e: if hasattr(e,"code"): print(e.code) if hasattr(e,"reason"): print(e.reason) return html
將爬下來(lái)的數(shù)據(jù)保存到表格中
ef saveData(datalist,savepath): print("保存中。。。") book = xlwt.Workbook(encoding="utf-8",style_compression=0) # 創(chuàng)建workbook對(duì)象 sheet = book.add_sheet('douban',cell_overwrite_ok=True) #創(chuàng)建工作表 cell_overwrite_ok表示直接覆蓋 col = ("電影詳情鏈接","影片中文網(wǎng)","影片外國(guó)名","圖片鏈接","評(píng)分","評(píng)價(jià)數(shù)","概況","相關(guān)信息") for i in range(0,8): sheet.write(0,i,col[i]) for i in range(0,250): print("第%d條" %(i+1)) data = datalist[i] for j in range(0,8): sheet.write(i+1,j,data[j]) book.save(savepath)
以上就是整個(gè)爬數(shù)據(jù)的整個(gè)程序,這僅僅是一個(gè)非常簡(jiǎn)單的爬取,如果想要爬更難的網(wǎng)頁(yè)需要實(shí)時(shí)分析
整個(gè)程序代碼
from bs4 import BeautifulSoup #網(wǎng)頁(yè)解析,獲取數(shù)據(jù) import sys #正則表達(dá)式,進(jìn)行文字匹配 import re import urllib.request,urllib.error #指定url,獲取網(wǎng)頁(yè)數(shù)據(jù) import xlwt #使用表格 import sqlite3 import lxml def main(): baseurl ="https://movie.douban.com/top250?start=" datalist = getData(baseurl) savepath=('douban.xls') saveData(datalist,savepath) #影片播放鏈接 findLink = re.compile(r'<a href="(.*?)" rel="external nofollow" rel="external nofollow" >') #創(chuàng)建正則表達(dá)式對(duì)象,表示規(guī)則(字符串的模式) #影片圖片 findImg = re.compile(r'<img.*src="(.*?)" width="100"/>',re.S)#re.S取消換行符 #影片片面 findtitle= re.compile(r'<span class="title">(.*?)</span>') #影片評(píng)分 fileRating = re.compile(r'<span class="rating_num" property="v:average">(.*?)</span>') #找到評(píng)價(jià)的人數(shù) findJudge = re.compile(r'<span>(\d*)人評(píng)價(jià)</span>') #找到概識(shí) findInq =re.compile(r'<span class="inq">(.*?)</span>') #找到影片的相關(guān)內(nèi)容 findBd = re.compile(r'<p class="">(.*?)</p>',re.S) def getData(baseurl): datalist=[] for i in range(0,10):#調(diào)用獲取頁(yè)面的函數(shù)10次 url = baseurl + str(i*25) html = askURl(url) #逐一解析 soup = BeautifulSoup(html,"html.parser") for item in soup.find_all('div',class_="item"): #print(item) data=[] item = str(item) link = re.findall(findLink,item)[0] #re庫(kù)用來(lái)通過(guò)正則表達(dá)式查找指定的字符串 data.append(link) titles =re.findall(findtitle,item) if(len(titles)==2): ctitle=titles[0].replace('\xa0',"") data.append(ctitle)#添加中文名 otitle = titles[1].replace("\xa0/\xa0Perfume:","") data.append(otitle)#添加外國(guó)名 else: data.append(titles[0]) data.append(' ')#外國(guó)名字留空 imgSrc = re.findall(findImg,item)[0] data.append(imgSrc) rating=re.findall(fileRating,item)[0] data.append(rating) judgenum = re.findall(findJudge,item)[0] data.append(judgenum) inq=re.findall(findInq,item) if len(inq) != 0: inq =inq[0].replace(".","") data.append(inq) else: data.append(" ") bd=re.findall(findBd,item)[0] bd=re.sub('<br(\s+)?/>(\s+)?'," ",bd) #去掉<br/> bd =re.sub('\xa0'," ",bd) data.append(bd.strip()) #去掉前后的空格 datalist.append(data) #把處理好的一部電影信息放入datalist return datalist #得到指定一個(gè)url的網(wǎng)頁(yè)內(nèi)容 def askURl(url): head = { "User-Agent": "Mozilla / 5.0(Windows NT 10.0;WOW64) Apple" +"WebKit / 537.36(KHTML, likeGecko) Chrome / 78.0.3904.108 Safari / 537.36" } #告訴豆瓣我們是瀏覽器我們可以接受什么水平的內(nèi)容 request = urllib.request.Request(url,headers=head) html="" try: response = urllib.request.urlopen(request) html = response.read().decode("utf-8") # print(html) except urllib.error.URLError as e: if hasattr(e,"code"): print(e.code) if hasattr(e,"reason"): print(e.reason) return html def saveData(datalist,savepath): print("保存中。。。") book = xlwt.Workbook(encoding="utf-8",style_compression=0) # 創(chuàng)建workbook對(duì)象 sheet = book.add_sheet('douban',cell_overwrite_ok=True) #創(chuàng)建工作表 cell_overwrite_ok表示直接覆蓋 col = ("電影詳情鏈接","影片中文網(wǎng)","影片外國(guó)名","圖片鏈接","評(píng)分","評(píng)價(jià)數(shù)","概況","相關(guān)信息") for i in range(0,8): sheet.write(0,i,col[i]) for i in range(0,250): print("第%d條" %(i+1)) data = datalist[i] for j in range(0,8): sheet.write(i+1,j,data[j]) book.save(savepath) if __name__ == '__main__': main()
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
使用python解析xml成對(duì)應(yīng)的html示例分享
這篇文章主要介紹了使用python解析xml成對(duì)應(yīng)的html示例,需要的朋友可以參考下2014-04-04PyCharm使用教程之搭建Python開(kāi)發(fā)環(huán)境
由于python的跨平臺(tái)性。在windows下和ubuntu下基本上沒(méi)什么差別。下面從幾個(gè)不步驟來(lái)搭建開(kāi)發(fā)環(huán)境。2016-06-06python中的位置參數(shù)和關(guān)鍵字參數(shù)詳解
位置參數(shù)和關(guān)鍵字參數(shù)是 Python 中的兩種不同類(lèi)型的函數(shù)參數(shù)傳遞方式,位置參數(shù)依賴(lài)于參數(shù)的位置順序,而關(guān)鍵字參數(shù)通過(guò)參數(shù)名傳遞,不受位置影響,本文通過(guò)代碼示例給大家詳細(xì)介紹了python中的位置參數(shù)和關(guān)鍵字參數(shù),需要的朋友可以參考下2023-12-12Python中數(shù)組,列表:冒號(hào)的靈活用法介紹(np數(shù)組,列表倒序)
下面小編就為大家分享一篇Python中數(shù)組,列表:冒號(hào)的靈活用法介紹(np數(shù)組,列表倒序),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-04-04圣誕節(jié)教你用Python繪制愛(ài)心圣誕樹(shù)
圣誕節(jié)快要到了,心血來(lái)潮,寫(xiě)段代碼給大家介紹下基于Python繪制愛(ài)心圣誕樹(shù)的方法,代碼簡(jiǎn)單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2021-12-12學(xué)習(xí)Python爬蟲(chóng)前必掌握知識(shí)點(diǎn)
這篇文章主要介紹了學(xué)習(xí)Python爬蟲(chóng)前,我們需要了解涉及爬蟲(chóng)的知識(shí)點(diǎn),學(xué)習(xí)爬蟲(chóng)的知識(shí)點(diǎn)比較多,我們一起學(xué)習(xí)爬蟲(chóng)吧2021-04-04matplotlib命令與格式之tick坐標(biāo)軸日期格式(設(shè)置日期主副刻度)
這篇文章主要介紹了matplotlib命令與格式之tick坐標(biāo)軸日期格式(設(shè)置日期主副刻度),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08Python如何快速生成本項(xiàng)目的requeirments.txt實(shí)現(xiàn)
本文主要介紹了Python如何快速生成本項(xiàng)目的requeirments.txt實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03