【爬虫实战项目一】Python爬取豆瓣电影榜单数据

目录

一、环境准备

二、编写代码

[2.1 分页分析](#2.1 分页分析)

[2.2 编码](#2.2 编码)


一、环境准备

安装requests和lxml

python 复制代码
pip install requests
pip install lxml

二、编写代码

2.1 分页分析

编写代码前我们先看看榜单的url

我们假如要爬取五页的数据,那么五个url分别是:

https://movie.douban.com/top250?start=0\&filter=
https://movie.douban.com/top250?start=25\&filter=
https://movie.douban.com/top250?start=50\&filter=
https://movie.douban.com/top250?start=75\&filter=
https://movie.douban.com/top250?start=100\&filter=

不难看出,规律在于start参数,每页有25条数据。

那么按照分页计算公式**(当前页数 - 1) * 每页数据量** 得出 代码逻辑。

2.2 编码

我们复制下xpath。

python 复制代码
import random
from lxml import etree
import requests
import time

# 请求头信息
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36'
}
# 共取5页数据
for i in range(1, 6):
    start = (i - 1) * 25
    url = f'https://movie.douban.com/top250?start={start}&filter='
    response = requests.get(url, headers=headers)
    tree = etree.HTML(response.text)
    div = tree.xpath('//*[@id="content"]/div/div[1]/ol/li/div')
    for d in div:
        # 获取当前电影标题
        title = d.xpath('.//span[@class="title"][1]/text()')[0]
        print(title)
    time.sleep(random.randint(1, 3))

成功爬取豆瓣电影TOP250榜单。

相关推荐
用户7783366132115 小时前
用 React Hook 封装搜索数据:useSerp 的防抖、缓存与错误处理
python·api
65岁退休Coder8 小时前
LangGraph v1.2.9 节点容错策略 & 流式输出 & 持久化记忆管理
后端·python·langchain
ikun_文11 小时前
Django框架路由Router的使用
python·pycharm·django
IvanCodes11 小时前
Python 基础语法(二):字符串与常用操作
python
昭昭日月明11 小时前
LangChain 生态:从链到代理,开发者需要掌握的三大核心
python·langchain·agent
Csvn11 小时前
🐍 Day 8:面向对象编程
后端·python
程序员天天困11 小时前
向量检索不准怎么办:混合检索与 Rerank 重排序召回优化实战
后端·python·ai编程
alphaTao13 小时前
LeetCode 每日一题 2026/8/24-2026/8/30
python·算法·leetcode
苏灿烤鱼13 小时前
当 AI Agent 遇见真实科学环境:深度拆解 Scientific Agent Skills,把"聊天机器人"变成"AI 科学家"
python·开源·agent
张文君13 小时前
ubuntu26.04坏道坏块分区隔离急速版260831-V0.12
linux·python