python爬虫爬取豆瓣影评
"""
使用selenium模拟点击影评‘全部’按钮
爬取影评第一页
获取用户名 评价 时间 星级 并保存在js文件中
获取下一页
"""
#用户名 评价 时间 星级
from selenium import webdriver #导入模拟点击库
import requests
import urllib3
import time
from bs4 import BeautifulSoup as bs
import json #用于处理json的库
# 模拟点击部分:打开指定网页
driver = webdriver.Chrome() # 实例化对象,新建一个浏览器对象
driver.get('https://movie.douban.com/subject/26631790/') # driver.get打开指定网页
#查找并点击评论‘全部’按钮
comment=driver.find_element_by_id('comments-section')
com_all=comment.find_element_by_class_name('pl')
com_all_a=com_all.find_element_by_tag_name('a')# 通过标签名查找
com_all_a.click() # click()点击选中的元素
#清空json文件
with open("douban.json", 'w', encoding='utf-8')as f:
pass
number=eval(input('输入你要需要的影评页数:'))
for i in range(number):
#打开指定网页
# driver=webdriver.Chrome() #实例化对象,新建一个浏览器对象
# driver.get('https://movie.douban.com/subject/26631790/comments?start={}&limit=20&status=P&sort=new_score'.format(20*i)) #driver.get打开指定网页
#获取用户名
#获取评论所有的标签
command=driver.find_element_by_id('comments')
com_list=command.find_elements_by_class_name('comment')
#此为静态网页所以不需要模拟用户滚动
for j in com_list:
#每一个j为一条评论
#用户名,评级,时间
head=j.find_element_by_class_name('comment-info')
#用户名
h_user=head.find_element_by_tag_name('a')
#评级
h_rat=head.find_element_by_class_name('rating')
h_rating=h_rat.get_attribute('title')
#时间
h_t=head.find_element_by_class_name('comment-time')
h_time=h_t.get_attribute('title')
#评论
content=j.find_element_by_class_name('short')
#合并
pinglun={"用户名":h_user.text,"评级":h_rating,"时间":h_time,"评论":content.text}
with open("douban.json", 'a', encoding="utf-8") as f:
f.write(json.dumps(pinglun,ensure_ascii=False))
print('第{}页评论爬取成功'.format(i+1))
time.sleep(3)
#模拟点击下一页方便下次爬取
paginator=driver.find_element_by_id('paginator')
paginator_next=paginator.find_element_by_class_name('next')
paginator_next.click() # click()点击选中的元素