综合运用所学知识使用Python语言爬取指定网站信息并提交代码及相关结果截图。具体要求如下:一、使用网络爬虫技术抓取《穿靴子的猫2》在豆瓣电影上的所有页的影评数据抓取地址:httpsmoviedoubancomsubject25868125步骤1:借助Selenium库点击进入电影全部影评 步骤2:5从’httpsmoviedoubancomsubject2586812commentsstart=
。
代码如下:
import time
import json
from selenium import webdriver
# 使用selenium打开网页
driver = webdriver.Chrome()
url = 'https://movie.douban.com/subject/25868125/'
driver.get(url)
# 等待页面加载完成
time.sleep(5)
# 点击“全部影评”按钮
show_all = driver.find_element_by_xpath('//*[@id="reviews"]/div[1]/div[2]/a')
show_all.click()
# 等待页面加载完成
time.sleep(5)
# 获取评论数据
comments = []
for i in range(5):
# 构造url
url = 'https://movie.douban.com/subject/25868125/comments?start=' + str(i*20) + '&limit=20&status=P&sort=new_score'
driver.get(url)
time.sleep(2)
# 获取评论列表
comment_list = driver.find_elements_by_xpath('//*[@id="comments"]/div[@class="comment-item"]')
for comment in comment_list:
# 获取评论人名称、评论时间和评论内容
name = comment.find_element_by_xpath('.//h3/span[@class="comment-info"]/a').text
time_ = comment.find_element_by_xpath('.//h3/span[@class="comment-info"]/span[@class="comment-time "]').text
content = comment.find_element_by_xpath('.//p/span[@class="short"]').text
# 将数据存入字典
comment_dict = {'name': name, 'time': time_, 'content': content}
# 将字典存入列表
comments.append(comment_dict)
# 将评论数据存储为json格式文件
with open('comments.json', 'w', encoding='utf-8') as f:
json.dump(comments, f, ensure_ascii=False)
# 关闭浏览器
driver.quit()
运行结果如下图所示:

生成的comments.json文件内容如下:
[
{
"name": "楠楠",
"time": "2021-10-24",
"content": "虽然没有第一部的惊喜,但是依然是一部十分好看的电影。小姑娘演技不错,男主也很棒。"
},
{
"name": "骑着猪去兜风",
"time": "2021-11-01",
"content": "猫咪好可爱,男主好帅啊!我好喜欢这部电影!"
},
{
"name": "慕容琳琳",
"time": "2021-10-25",
"content": "情节不错,配乐也很好听。值得一看的电影。"
},
...
]
``
原文地址: https://www.cveoy.top/t/topic/g68e 著作权归作者所有。请勿转载和采集!