Python爬虫:urllib_ajax的get请求豆瓣电影前十页(08)

复制代码
# https://movie.douban.com/j/chart/top_list?type=5&interval_id=100%3A90&action=&
# start=0&limit=20
import urllib.parse
import urllib.request



# 下载豆瓣电影前10页的数据
# (1)请求对象的定制
# (2)获取响应的数据
# (3)下载数据

def create_request(page):
    base_url = 'https://movie.douban.com/j/chart/top_list?type=5&interval_id=100%3A90&action=&'

    data = {
        'start':(page - 1) * 20,
        'limit':20
    }

    data = urllib.parse.urlencode(data)

    url = base_url + data


    headers = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36'}

    request = urllib.request.Request(url=url, headers=headers)

    return request


def get_content(request):
    response = urllib.request.urlopen(request)
    content = response.read().decode('utf-8')
    return content


def down_load(page, content):
    with open('douban_' + str(page) + '.json', 'w', encoding='utf-8') as fp:
        fp.write(content)


#程序的入口
if __name__=='__main__':
    start_page = int(input('请输入起始的页码'))
    end_page = int(input('请输入结束的页码'))
    for page in range(start_page, end_page + 1):
#       每一页都有自己的请求对象的定制
        request = create_request(page)
#       获取响应的数据
        content = get_content(request)
#       下载
        down_load(page, content)

这个就是一个综合型的应用了,这个需要扎实的基本功和对于函数调用的理解,然后根据函数的编写去做一个页面的爬取,我们要先分析好网址域名和后面的参数的组成规律,然后再去爬取,在这里的前提先了解,怎么找到这个网址,到浏览器里面检查的network,往豆瓣网站往下拉,去寻找一个含有list的文件,在里面找请求的url,找到如下

网址已做拆分

豆瓣网站的第一页

https://movie.douban.com/j/chart/top_list?type=5\&interval_id=100%3A90\&action=\&

start=0&limit=20

豆瓣网址的第二页

https://movie.douban.com/j/chart/top_list?type=5\&interval_id=100%3A90\&action=\&

start=20&limit=20

豆瓣网址的第三页

https://movie.douban.com/j/chart/top_list?type=5\&interval_id=100%3A90\&action=\&

start=40&limit=20

我们发现页面和start是有规律可循的

规律就是 (page - 1)* 20

然后编写代码就好

拆分成三个大部分。

相关推荐
心中有国也有家2 小时前
GE图引擎深度解析——CANN的计算图优化与执行引擎
人工智能·pytorch·python·学习·numpy
卷毛的技术笔记4 小时前
告别硬编码!Spring AI Alibaba 实现 AI Agent 智能工具调用(Tool Calling)
java·人工智能·后端·python·spring·ai编程
编程大师哥4 小时前
匿名函数 lambda + 高阶函数
java·python·算法
vb2008114 小时前
FastAPI APIRouter
开发语言·python
adrninistrat0r4 小时前
Java调用链MCP分析工具
java·python·ai编程
杨充4 小时前
1.3 浮点型数据设计灵魂
开发语言·python·算法
meilindehuzi_a5 小时前
深入浅出数据结构:Python 字典(Dict)与集合(Set)的哈希表底层全链路追踪
数据结构·python·散列表
Lucas凉皮5 小时前
20243408 2025-2026-2 《Python程序设计》综合实践报告
python·实验报告
键盘上的猫头鹰5 小时前
【MySQL 教程(八)】索引、事务、用户管理、导入导出与分页查询
数据库·python·mysql
薛定谔的猫-菜鸟程序员6 小时前
2小时智能体开发一个智能体?我用CodeArts Agent 和 AtomCode 开发了一个适老化智能体。
人工智能·python·agent