Python–爬取豆瓣影评①并保存在本地
提示:
①.本文只提供能爬取豆瓣影评前二十页(豆瓣影评前二十页不需要登录)的内容,若需要爬取更多页,请看“Python–爬取豆瓣影评②并保存在本地” ②.本文可爬取阿甘正传的观影影评,若您需要爬取别的电影影评,需要修改爬取的url以及url的规律(但是规律一般一致)。 ③.本文不做任何教学,只将代码附上,有需要学习的或者借鉴的从代码中自行学习!,介意勿看。
完整代码附上
"""
1.爬取豆瓣的短影评 ----阿甘正传
2.保存在本地.
-------- 只能查看前200条影评
"""
import requests
import re
import time
import random
class Spider_db:
def __init__(self):
self.comment_url = "https://movie.douban.com/subject/1292720/comments?start={}&limit=20&status=P&sort=new_score"
self.comment_headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36 Edg/96.0.1054.34"}
def get_comment_url(self):
url_list = []
for i in range(10):
url_list.append(self.comment_url.format(i * 20))
return url_list
def comment_db(self, url):
resp = requests.get(url=url, headers=self.comment_headers)
comments = re.findall('<span class="short">(.*)</span>', resp.content.decode())
return comments
def save_text(self, db_text, page_num):
file_path = "阿甘正传--影评第{}页".format(page_num)
with open(file_path, "a+", encoding="utf-8") as f:
f.write(db_text)
f.write("\n")
def run(self):
comment_list = self.get_comment_url()
for url in comment_list:
comments = self.comment_db(url)
page_num = comment_list.index(url) + 1
for content in comments:
self.save_text(content, page_num)
print("写入成功")
time.sleep(random.random() * 5)
if __name__ == '__main__':
spider = Spider_db()
spider.run()
效果图
注意: ①:此代码不能保证一直能够爬取,因为url地址及规律会变化。最后一次执行时间为:2021-12-04
②:若不能执行私信我,我会更新一下内容!
|