[爬虫]爬取豆瓣任意电影的

最近好像上映了不少电影,而且我好久没看过豆瓣了,这里给大家分享一个爬取豆瓣评论的selenium脚本。

首先我们打开电影的短片区:

这里大家注意,虽然全部写着有10万多条,其实豆瓣电影里只显示前600条。。。。。

1、先将selenium的相关包导进来

import time
import tqdm
import random
import requests
import json
import pandas as pd
import os
from selenium import webdriver
from selenium.webdriver.common.by import By

2、用edge浏览器打开相关电影评论网页

browser = webdriver.Edge()
time.sleep(5)
browser.get('https://movie.douban.com/subject/26925611/comments?percent_type=h&limit=20&status=P&sort=new_score')

3、用xpath语句定位想要爬取的数据,这里就爬了评论数据来做lda等后续的数据分析

from selenium.common.exceptions import NoSuchElementException, StaleElementReferenceException, ElementClickInterceptedException
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

max_clicks = 100 
click_count = 0  
comments=[]
ratings=[]
urls=[]
try:
                       
                while click_count < max_clicks:
                        try:
                                li_list = browser.find_elements_by_xpath('//div[@id="comments"]/div')
                                for li in li_list:
                                        try:
                                                comment = li.find_element_by_xpath('.//span[@class="short"]').text
                                                print("comment:>>",comment)
                                                comments.append(comment)
                                        except:
                                                pass
                                next_link = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.CLASS_NAME, "next")))
                                next_link.click()
                                click_count += 1  # 增加点击次数计数器
                                time.sleep(2)  # 等待页面加载
                        except Exception as e:
                                print("无法找到或点击按钮:", e)
                                break

except (StaleElementReferenceException, ElementClickInterceptedException):
              pass  # 元素不可用或者无法点击,继续下一次循环处理下一页内容
df = pd.DataFrame({'comment':comments,'rating':0})
df.to_csv("./comments.csv", index=False)

4、结果如下:

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值