前言
閉關幾個月,今天爲大家帶來利用Python爬蟲抓取豆瓣電影《魔女2》影評,廢話不多說。
爬取了6月7月25的影片數據,Let's start happily
開發工具
Python版本: 3.6.4
相關模塊:
requests模塊
json模塊
re模塊
os模塊
pandas模塊
time模塊
環境搭建
安裝Python並添加到環境變量,pip安裝需要的相關模塊即可。
思路分析
本文以爬取豆瓣電影《魔女2》影評,講解如何爬取豆瓣電影《魔女2》評論!
前期準備
1.獲取頁面內容
# 爬取頁面 url
douban_url = 'https://movie.douban.com/subject/34832354/comments?start=40&limit=20&status=P&sort=new_score'
# requests 發送請求
get_response = requests.get(douban_url)
# 將返回的響應碼轉換成文本(整個網頁)
get_data = get_response.text
2.分析頁面內容,獲取我們想要的內容
- 瀏覽器中打開我們要爬取的頁面
- 按F12進入開發者工具,查看我們想要的數據在哪裏
- 這裏我們只要 評論人+評論內
3.利用re模塊解析數據
def get_nextUrl(html):
"""抓取下一個頁面的 url"""
try:
# 找到下一頁的 url
url = html.find('a', 'next').attrs['href']
# print(url)
next_start = re.search(r'[0-9]\d{0,5}', url).group(0)
print("已經到 " + str(next_start) + " 請稍等一會兒\n")
next_url = "https://movie.douban.com/subject/34832354/comments?percent_type=" \
"&start={}&limit=20&status=P&sort=new_score&comments_only=1&ck=Cuyu".format(next_start)
# print(next_url)
return next_url
except:
print("到底了~")
運行結果
4.代碼實現
def get_html(url):
headers = Agent_info()
try:
r = requests.get(url=url, headers=headers, timeout=30)
r.encoding = r.apparent_encoding
status = r.status_code # 爬蟲的狀態
datas = json.loads(r.text)["html"]
str_html = "<html>{}</html>".format(datas)
html = BeautifulSoup(str_html, "html.parser")
print("爬蟲狀態碼: " + str(status))
# print(type(html))
return html
except Exception as e:
print("數據爬取失敗!")
print(e)
def etl_data(html):
"""提取出我們想要的數據"""
comments = html.find_all('div', 'comment-item')
# print(comments[0])
datas = []
for span in comments:
# 短評發表的時間
times = span.find('span', 'comment-time').attrs['title']
# 用戶名
name = span.find('a').attrs["title"]
# 用戶評分星級
try:
level = span.find('span', 'rating').attrs['class'][0][-2:]
if (level == '10'):
level = "一星"
elif (level == '20'):
level = "二星"
elif (level == '30'):
level = "三星"
elif (level == '40'):
level = "四星"
elif (level == '50'):
level = "五星"
except Exception as e:
level = "無評價"
content = span.find('span', 'short').string.strip()
content = re.sub(r'\n', '', content)
love_point = span.find('span', 'vote-count').string.strip()
arr = [times, name, level, content, love_point]
datas.append(arr)
df = pd.DataFrame(datas)
df.columns = ["時間", "用戶", "星級", "短評", "支持數"]
# print(arr)
return df
#代碼測試2022.7.28無異常,點贊超過100,更新爬蟲豆瓣讀書TOP250