Python爬取豆瓣數(shù)據(jù)實現(xiàn)過程解析
代碼如下
from bs4 import BeautifulSoup #網(wǎng)頁解析,獲取數(shù)據(jù) import sys #正則表達(dá)式,進(jìn)行文字匹配 import re import urllib.request,urllib.error #指定url,獲取網(wǎng)頁數(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)
這個放在末尾
if __name__ == '__main__':
main()
不難看出這是主函數(shù),里面的話是對子函數(shù)的調(diào)用,下面是第三個步驟:子函數(shù)的代碼
對網(wǎng)頁正則表達(dá)提?。ǚ旁谥骱瘮?shù)的后面就可以)
findLink = re.compile(r'<a href="(.*?)" rel="external nofollow" rel="external nofollow" >') #創(chuàng)建正則表達(dá)式對象,表示規(guī)則(字符串的模式)
#影片圖片
findImg = re.compile(r'<img.*src="(.*?)" width="100"/>',re.S)#re.S取消換行符
#影片片面
findtitle= re.compile(r'<span class="title">(.*?)</span>')
#影片評分
fileRating = re.compile(r'<span class="rating_num" property="v:average">(.*?)</span>')
#找到評價的人數(shù)
findJudge = re.compile(r'<span>(\d*)人評價</span>')
#找到概識
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)用獲取頁面的函數(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庫用來通過正則表達(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)#添加外國名
else:
data.append(titles[0])
data.append(' ')#外國名字留空
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)頁內(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
將爬下來的數(shù)據(jù)保存到表格中
ef saveData(datalist,savepath):
print("保存中。。。")
book = xlwt.Workbook(encoding="utf-8",style_compression=0) # 創(chuàng)建workbook對象
sheet = book.add_sheet('douban',cell_overwrite_ok=True) #創(chuàng)建工作表 cell_overwrite_ok表示直接覆蓋
col = ("電影詳情鏈接","影片中文網(wǎng)","影片外國名","圖片鏈接","評分","評價數(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)
以上就是整個爬數(shù)據(jù)的整個程序,這僅僅是一個非常簡單的爬取,如果想要爬更難的網(wǎng)頁需要實時分析
整個程序代碼
from bs4 import BeautifulSoup #網(wǎng)頁解析,獲取數(shù)據(jù)
import sys #正則表達(dá)式,進(jìn)行文字匹配
import re
import urllib.request,urllib.error #指定url,獲取網(wǎng)頁數(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á)式對象,表示規(guī)則(字符串的模式)
#影片圖片
findImg = re.compile(r'<img.*src="(.*?)" width="100"/>',re.S)#re.S取消換行符
#影片片面
findtitle= re.compile(r'<span class="title">(.*?)</span>')
#影片評分
fileRating = re.compile(r'<span class="rating_num" property="v:average">(.*?)</span>')
#找到評價的人數(shù)
findJudge = re.compile(r'<span>(\d*)人評價</span>')
#找到概識
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)用獲取頁面的函數(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庫用來通過正則表達(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)#添加外國名
else:
data.append(titles[0])
data.append(' ')#外國名字留空
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
#得到指定一個url的網(wǎng)頁內(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對象
sheet = book.add_sheet('douban',cell_overwrite_ok=True) #創(chuàng)建工作表 cell_overwrite_ok表示直接覆蓋
col = ("電影詳情鏈接","影片中文網(wǎng)","影片外國名","圖片鏈接","評分","評價數(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()
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
使用python解析xml成對應(yīng)的html示例分享
這篇文章主要介紹了使用python解析xml成對應(yīng)的html示例,需要的朋友可以參考下2014-04-04
PyCharm使用教程之搭建Python開發(fā)環(huán)境
由于python的跨平臺性。在windows下和ubuntu下基本上沒什么差別。下面從幾個不步驟來搭建開發(fā)環(huán)境。2016-06-06
python中的位置參數(shù)和關(guān)鍵字參數(shù)詳解
位置參數(shù)和關(guān)鍵字參數(shù)是 Python 中的兩種不同類型的函數(shù)參數(shù)傳遞方式,位置參數(shù)依賴于參數(shù)的位置順序,而關(guān)鍵字參數(shù)通過參數(shù)名傳遞,不受位置影響,本文通過代碼示例給大家詳細(xì)介紹了python中的位置參數(shù)和關(guān)鍵字參數(shù),需要的朋友可以參考下2023-12-12
Python中數(shù)組,列表:冒號的靈活用法介紹(np數(shù)組,列表倒序)
下面小編就為大家分享一篇Python中數(shù)組,列表:冒號的靈活用法介紹(np數(shù)組,列表倒序),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04
學(xué)習(xí)Python爬蟲前必掌握知識點(diǎn)
這篇文章主要介紹了學(xué)習(xí)Python爬蟲前,我們需要了解涉及爬蟲的知識點(diǎn),學(xué)習(xí)爬蟲的知識點(diǎn)比較多,我們一起學(xué)習(xí)爬蟲吧2021-04-04
matplotlib命令與格式之tick坐標(biāo)軸日期格式(設(shè)置日期主副刻度)
這篇文章主要介紹了matplotlib命令與格式之tick坐標(biāo)軸日期格式(設(shè)置日期主副刻度),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
Python如何快速生成本項目的requeirments.txt實現(xiàn)
本文主要介紹了Python如何快速生成本項目的requeirments.txt實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03

