由于豆瓣电影对爬虫有限制,需要先设置一些请求头信息,以免被禁止访问。

import requests
from bs4 import BeautifulSoup

# 设置请求头信息
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}

# 穿靴子的猫2在豆瓣电影上的链接
url = 'https://movie.douban.com/subject/25868125/'

# 发送请求
response = requests.get(url, headers=headers)

# 使用BeautifulSoup解析网页
soup = BeautifulSoup(response.text, 'html.parser')

接下来,我们需要获取这部电影的总评价数,以便计算需要爬取的页数。

# 获取总评价数
total_comment = soup.find('span', {'class': 'rating_num'}).string
print('总评价数:' + total_comment)

# 计算总页数
total_page = int(total_comment) // 20 + 1
print('总页数:' + str(total_page))

然后,我们需要循环爬取每一页的影评数据,并将数据存储到文件中。

# 循环爬取每一页的影评数据
for i in range(total_page):
    # 构造URL
    page_url = url + 'comments?start=' + str(i * 20) + '&limit=20&sort=new_score&status=P'

    # 发送请求
    response = requests.get(page_url, headers=headers)

    # 使用BeautifulSoup解析网页
    soup = BeautifulSoup(response.text, 'html.parser')

    # 获取影评
    comments = soup.find_all('span', {'class': 'short'})

    # 将影评写入文件
    with open('comments.txt', 'a', encoding='utf-8') as f:
        for comment in comments:
            f.write(comment.get_text() + '\n')
Python爬虫实战:抓取《穿靴子的猫2》豆瓣电影影评

原文地址: https://www.cveoy.top/t/topic/oA22 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录