综合运用所学知识使用Python语言爬取指定网站信息并提交代码及相关结果截图。具体要求如下:一、使用网络爬虫技术抓取《穿靴子的猫2》在豆瓣电影上的所有页的影评数据抓取地址:httpsmoviedoubancomsubject25868125步骤1:借助Selenium库全部使用bs4定位元素设置浏览器使用绝对路径点击进入电影全部影评步骤2:从’httpsmoviedoubancomsubject2
注:以下代码需要使用Selenium、BeautifulSoup、json库,需提前安装。
import time from selenium import webdriver from bs4 import BeautifulSoup import json
设置浏览器驱动路径
driver_path = 'C:/chromedriver_win32/chromedriver.exe'
创建浏览器对象
browser = webdriver.Chrome(executable_path=driver_path)
访问电影的评论页面
url = 'https://movie.douban.com/subject/25868125/comments?status=P' browser.get(url)
点击“全部”按钮,展开全部评论
all_button = browser.find_element_by_xpath('//*[@id="comments-section"]/div[1]/div[2]/a') all_button.click() time.sleep(1)
获取全部评论页数
soup = BeautifulSoup(browser.page_source, 'html.parser') page_info = soup.select('.comment-page > a')[-2].get_text() total_page = int(page_info)
循环遍历每一页的评论
comments = [] for i in range(0, total_page): # 获取当前页的评论 url = 'https://movie.douban.com/subject/25868125/comments?start={}&limit=20&status=P&sort=new_score'.format(i*20) browser.get(url) soup = BeautifulSoup(browser.page_source, 'html.parser') comment_list = soup.select('#comments > .comment-item')
# 解析评论信息
for comment_item in comment_list:
comment = {}
name = comment_item.select('.comment-info > a')[0].get_text().strip()
time = comment_item.select('.comment-info > span')[0].get_text().strip()
content = comment_item.select('.short')[0].get_text().strip()
comment['name'] = name
comment['time'] = time
comment['content'] = content
comments.append(comment)
保存评论数据为json文件
with open('comments.json', 'w', encoding='utf-8') as f: json.dump(comments, f, ensure_ascii=False)
关闭浏览器
browser.quit(
原文地址: https://www.cveoy.top/t/topic/g7t1 著作权归作者所有。请勿转载和采集!