概述:
爬取豆瓣影評數據步驟:
1、獲取網頁請求
2、解析獲取的網頁
3、提速數據
4、保存文件
源代碼:
# 1、導入需要的庫
import urllib.request
from bs4 import BeautifulSoup
# 隨機數的庫
import random
# 時間庫
import time
# 表格庫
import csv
# 2、分多個瀏覽器訪問豆瓣網,防止訪問多頁時被拒絕
# 每個瀏覽器在請求數據的時候,請求頭是不一樣
# 計算機命名規則:駝峰命名法
# url:傳值過來的訪問地址
def getRequest(url):
# 谷歌瀏覽器
header1 = {
"Host":"movie.douban.com",
"User-Agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"
}
# 火狐瀏覽器
header2 = {
"Host": "movie.douban.com",
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; rv:73.0) Gecko/20100101 Firefox/73.0"
}
# 將瀏覽器裝入列表里
list = [header1,header2]
# 隨機取一個請求頭 len(list)-1:列表長度-1
index = random.randint(0,len(list)-1)
# 隨機用一個請求頭,開始訪問地址
req = urllib.request.Request(url=url,headers=list[index])
# 返回結果
return req
# 封裝函數,爬取數據
def getData(url,commentAll):
# 獲取處理后的請求
req = getRequest(url)
# 打開網址
html = urllib.request.urlopen(req)
# 讀取數據(data得到所有數據)
data = html.read()
# 輸出爬取到的所有數據,進制形式顯示
# print(data)
# 定義soup對象,解析網頁
soup = BeautifulSoup(data,"html.parser")
# 找到裝有所有評論的id名為comments的div
# ["數據"] 數組里只有一個元素----數據
comments = soup.select("#comments")[0]
# print(comments)
# 讀取到每一條評論,div的class名為comment-item
items = comments.select(".comment-item")
# print(items)
# 循環遍歷每一條評論
for i in items:
# 找到裝着用戶名和星級的span標簽,class名為comment-info
info = i.select(".comment-info")[0]
# print(info)
# 讀出用戶名的a標簽里面的字符串用戶名 [<a></a>]
# author = info.select("a")[0].string 數據在列表里
author = info.find("a").string
# print(author)
# 取星級,找到裝着星級的span標簽,讀取title值
# ["看過",星級,時間]
star = info.select("span")[1]["title"]
# print(star)
# 取評論,找到class名為short的p標簽
short = i.select(".short")[0].string
# print(short)
# 將 用戶名、星級、評論 裝入在字典里面
talk = {"author":author,"star":star,"short":short}
# print(talk)
# 將字典類型的數據,加到列表里面
commentAll.append(talk)
# 返回整個列表
return commentAll
# 封裝函數,把數據裝入表格中
def writeInto(commentAll):
# 打開表格 as從命名 file
# 參數1:表格名稱
# 參數2:"a+"追加模式 "w"寫入模式 "r"讀取模式
# w:writer r:read a:append
# wb二進制,不帶b就是文本
# 參數3:數據格式為utf-8
# 參數4:newline 新行,空行
with open("douban.csv","a+",encoding="utf-8",newline="") as file:
# 向表格寫入數據
writer = csv.writer(file)
# 數據在commentAll列表,循環遍歷列表,讀取數據
for i in commentAll:
# 讀取每一個字段 用戶名、星級、評論
info = [i["author"],i["star"],i["short"]]
# 把數據寫入表格
writer.writerow(info)
# 關閉表格
file.close()
# 函數的入口
# 直接輸入main,有提示
if __name__ == '__main__':
# 初始化一個空列表,將得到的所有數據
commentAll = []
# range()產生序列 0.1.2,爬取3頁
for i in range(0,3):
# 爬取的網頁地址
# limit=20 每一頁讀取20條數據
# start = 80 從第幾條讀取數據 20-39 40-59 60-79 80-99
url = "https://movie.douban.com/subject/25931446/comments?start=%d&limit=20&sort=new_score&status=P"%(i*20)
# 調用函數,爬取數據
getData(url,commentAll)
# 每爬取一個頁面數據,休息10秒,防止被封號
time.sleep(10)
# 調用函數,爬取完數據,裝入表格
writeInto(commentAll)
# 將表格用 記事本 打開,另存為ANSI格式
# 如果你要操作數據,還要轉回utf-8