综合运用所学知识使用Python语言爬取指定网站信息并提交代码及相关结果截图。具体要求如下:一、使用网络爬虫技术抓取《穿靴子的猫2》在豆瓣电影上的所有页的影评数据抓取地址:httpsmoviedoubancomsubject25868125步骤1:借助Selenium库全部使用bs4定位元素点击进入电影全部影评步骤2:从’httpsmoviedoubancomsubject25868125comm
导入需要的库
import time import json from bs4 import BeautifulSoup from selenium import webdriver
设置浏览器驱动路径
driver_path = 'chromedriver.exe'
设置电影页面地址
movie_url = 'https://movie.douban.com/subject/25868125/'
设置电影评论页面地址
comment_url = 'https://movie.douban.com/subject/25868125/comments?start={}&limit=20&status=P&sort=new_score'
设置评论页数
page_number = 3
初始化浏览器对象
driver = webdriver.Chrome(executable_path=driver_path)
打开电影页面
driver.get(movie_url)
等待页面加载完成
time.sleep(3)
定位全部影评按钮
all_comment_button = driver.find_element_by_class_name('more')
点击进入全部影评页面
all_comment_button.click()
等待页面加载完成
time.sleep(3)
初始化评论列表
comments = []
循环抓取每一页的评论
for i in range(page_number): # 构造评论页面地址 url = comment_url.format(i * 20)
# 打开评论页面
driver.get(url)
# 等待页面加载完成
time.sleep(3)
# 获取页面源码
html = driver.page_source
# 解析页面源码
soup = BeautifulSoup(html, 'html.parser')
# 获取评论列表
comment_list = soup.find('div', class_='comment-list')
# 遍历评论列表,抓取评论信息
for comment in comment_list.find_all('div', class_='comment-item'):
# 获取评论人名称
name = comment.find('span', class_='comment-info').a.string.strip()
# 获取评论时间
time = comment.find('span', class_='comment-time')['title']
# 获取评论内容
content = comment.find('span', class_='short').string.strip()
# 构造评论字典
comment_dict = {
'name': name,
'time': time,
'content': content
}
# 将评论字典添加到评论列表中
comments.append(comment_dict)
关闭浏览器对象
driver.quit()
将评论列表以json格式存储到文件中
with open('comments.json', 'w', encoding='utf-8') as f: json.dump(comments, f, ensure_ascii=False)
print('评论数据抓取完成!'
原文地址: http://www.cveoy.top/t/topic/g7mr 著作权归作者所有。请勿转载和采集!