本教程使用Python爬取豆瓣电影评论,涵盖了Selenium库、BeautifulSoup库、Requests库的使用,以及如何处理网站反爬虫机制。

代码示例:

import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 创建浏览器对象
driver = webdriver.Chrome()

# 访问url地址
url = 'https://movie.douban.com/subject/25868125/'
driver.get(url)

# 设置浏览器窗口最大化
driver.maximize_window()

# 设置请求头部信息
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
    'Cookie': '你的Cookie',
    'Referer': 'https://movie.douban.com/subject/25868125/'
}

# 发送请求获取页面内容
res = requests.get(url, headers=headers)
soup = BeautifulSoup(res.text, 'html.parser')

# 解析页面内容获取影评数据
comments = soup.select('.comment-item')
for comment in comments:
    name = comment.select('.comment-info > a')[0].text.strip()
    time = comment.select('.comment-info > span')[0].text.strip()
    content = comment.select('.short')[0].text.strip()
    print(name, time, content)

# 循环爬取所有页的影评数据
while True:
    try:
        # 查找'下一页'按钮元素,若找到则点击,否则退出循环
        next_button = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, '.comment .next a'))
        )
        next_button.click()
    except:
        break

# 关闭浏览器
driver.close()

注意事项:

  1. 需要安装Chrome浏览器和对应版本的ChromeDriver,否则会报错。
  2. 需要将代码中的'你的Cookie'替换成自己的豆瓣账号的Cookie。
  3. 现在豆瓣网站的反爬虫机制比较严格,爬取过程中可能会被检测出来,建议使用代理IP或者降低爬取频率来避免被封禁。
  4. 需要注意页面元素的定位方式和等待时间,否则会出现元素找不到或者超时的问题。可以使用Selenium提供的等待方法来解决这些问题。

更多内容:

  • 使用Selenium库模拟浏览器操作,例如点击、输入、滚动等。
  • 使用BeautifulSoup库解析页面内容,获取所需数据。
  • 使用Requests库发送请求获取网页内容。
  • 如何处理网站反爬虫机制。
  • 如何使用代理IP来隐藏自己的真实IP地址。

本教程仅供学习交流,请勿用于任何非法目的。

豆瓣电影评论爬取教程 - Python实现

原文地址: https://www.cveoy.top/t/topic/oA6p 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录