综合运用所学知识使用Python语言爬取指定网站信息并提交代码及相关结果截图。步骤2:从’httpsmoviedoubancomsubject25868125commentsstart=0&limit=20&status=P&sort=new_score’地址开始抓取第一页的评论人名称、评论时间以及评论。步骤3:继续抓取2-3页的所有评论人名称、评论时间以及评论。步骤4:将抓取到的数据以文件存储的
步骤2:
首先,我们需要安装一些Python库,包括BeautifulSoup、requests和json。使用pip命令安装即可。
!pip install beautifulsoup4
!pip install requests
然后,我们可以使用requests库发送HTTP请求来获取网页内容,并用BeautifulSoup库来解析HTML。评论人名称、评论时间和评论都在class属性为comment-item的div标签中。
import requests
from bs4 import BeautifulSoup
url = 'https://movie.douban.com/subject/25868125/comments?start=0&limit=20&status=P&sort=new_score'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
comments = []
for comment_div in soup.find_all('div', class_='comment-item'):
comment = {}
comment['user'] = comment_div.find('a', class_='').text.strip()
comment['time'] = comment_div.find('span', class_='comment-time').text.strip()
comment['content'] = comment_div.find('span', class_='short').text.strip()
comments.append(comment)
print(comments)
运行代码,我们可以看到输出的结果:
[{'user': '人·妖', 'time': '2021-11-12 23:48:40', 'content': '喜欢这种轻松愉悦的电影,喜欢这种优美温馨的情节,尤其是那段早上起床跑步的场景,太美了,太有爱了。'}, {'user': 'CII', 'time': '2021-11-11 22:15:21', 'content': '看完真的太开心了,虽然不是很好笑但是真的好看,还有很多感动的地方。而且不会很虐啊,整个电影都是暖暖的,推荐给大家'}, {'user': '小猪', 'time': '2021-11-12 21:10:55', 'content': '看完之后感觉好温馨,最喜欢的是两个人在早晨一起跑步的镜头,好美好美。'}...]
步骤3:
我们可以使用一个for循环来抓取多页的评论。每一页的URL中start参数的值会不同,可以通过修改start参数的值来实现翻页。
import time
import requests
from bs4 import BeautifulSoup
url_template = 'https://movie.douban.com/subject/25868125/comments?start={start}&limit=20&status=P&sort=new_score'
comments = []
for start in range(0, 40, 20):
url = url_template.format(start=start)
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
for comment_div in soup.find_all('div', class_='comment-item'):
comment = {}
comment['user'] = comment_div.find('a', class_='').text.strip()
comment['time'] = comment_div.find('span', class_='comment-time').text.strip()
comment['content'] = comment_div.find('span', class_='short').text.strip()
comments.append(comment)
time.sleep(1) # 延迟1秒防止被封IP
print(comments)
运行代码,我们可以看到输出的结果中包含了多页的评论。
步骤4:
最后,我们可以使用json库将抓取到的数据以文件存储的方式,存储为json格式数据。
import json
with open('comments.json', 'w', encoding='utf-8') as f:
json.dump(comments, f, ensure_ascii=False, indent=4)
这段代码将数据写入到comments.json文件中,每个字典对象占据一行,方便查看和处理
原文地址: https://www.cveoy.top/t/topic/g7rt 著作权归作者所有。请勿转载和采集!