使用到的库:requests、lxml、pandas、os
爬取思路:通过requests请求直接请求url得到网页的原html代码,豆瓣的短评都是直接储存到html当中的,所以直接使用xpath对网页进行解析并爬取即可得到评论的时间,内容和评价。
使用的浏览器:google,
插件:XpathHelper (具体安装方法可以在网上搜索)
我们通过检查得到评论储存的位置
通过xpath提取到评论的内容
通过相同的方法,我们可以得到评论的时间、评价等内容。
接下来是代码部分,我就将整个代码放进来了,只要导入对应的库应该都是可以正常运行的。
import requests
from lxml import etree
import pandas as pd
import os
movie_id = input('请输入电影ID: ')
url = f'https://movie.douban.com/subject/{movie_id}/comments?start=20&limit=100&status=P&sort=new_score'
# url = 'https://movie.douban.com/subject/1291561/comments?start=20&limit=20&status=P&sort=new_score'
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'
}
response = requests.get(url=url, headers=headers)
response.encoding = 'utf-8'
# 使用lxml解析数据
tree = etree.HTML(response.text)
# 提取数据
top_title = tree.xpath('string(//div[@id="content"]/h1)')
times = tree.xpath('//div[@class="comment"]/h3/span/span[3]/@title')
contents = tree.xpath('//div[@class="comment"]/p/span[@class="short"]/text()')
rates_text = tree.xpath('//div[@class="comment"]/h3/span/span[2]/@title')
# 过滤掉不符合评价文本的内容
filtered_rates_text = [rate for rate in rates_text if rate in ['力荐', '推荐', '还行', '较差', '很差']]
rates = [5 if rate == '力荐' else 4 if rate == '推荐' else 3 if rate == '还行' else 2 if rate == '较差' else 1 for rate in filtered_rates_text]
# 转换为DataFrame
data = {
'时间': times[:len(filtered_rates_text)], # 只获取评价文本对应的时间数据
'评论内容': contents[:len(filtered_rates_text)], # 只获取评价文本对应的评论内容数据
'评价': rates
}
df = pd.DataFrame(data)
# 设定文件名并检查文件是否存在,添加新内容或创建新文件
output_file_name = f'{top_title.strip()}.xlsx'
output_file_path = 'D:/moviecomments/' + output_file_name
df.to_excel(output_file_path, index=False)
if os.path.exists(output_file_name):
existing_df = pd.read_excel(output_file_name)
new_to_add = df[~df['时间'].isin(existing_df['时间'])] # 检查时间是否存在重复的内容
if not new_to_add.empty:
combined_df = pd.concat([existing_df, new_to_add], ignore_index=True)
combined_df.to_excel(output_file_name, index=False)
# 打印本次输入的数据量
print(f'本次一共输入了 {len(filtered_rates_text)} 条数据')
print(f'已保存至 {output_file_name} 文件')
注意事项:
1.豆瓣评论在网页html里使用的是力荐、推荐等字眼,我将其转换成了数字形式保存。
2.其中的output_file_path我们需要换成我们自己储存的文件路径。