爬虫-获取豆瓣Top250信息

复制代码
import time
import requests
from lxml import etree
i = 0
for item in range(0, 275, 25):
    url = f'https://movie.douban.com/top250?start={item}&filter='
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36"
    }
    res = requests.get(url, headers=headers)
    res.encoding = res.apparent_encoding
    page_source = res.text
    page_tree = etree.HTML(page_source)
    page_data = page_tree.xpath('//*[@id="content"]//*[@class="item"]/div[2]')
    i +=1
    print(f'正在抓取第{i}页')
    with open('250.csv', 'a') as f:
        for item in page_data:
            name = item.xpath('./div[1]/a/span[1]/text()')[0]
            fen = item.xpath('./div[2]/div[@class="star"]/span[2]/text()')[0]
            num = item.xpath('./div[2]/div[@class="star"]/span[4]/text()')[0]
            year = item.xpath('./div[2]/p/text()[2]')[0].split()[0]
            country = item.xpath('./div[2]/p/text()[2]')[0].split('/')[1].strip()
            type = item.xpath('./div[2]/p/text()[2]')[0].split('/')[2].strip()
            website = item.xpath('./div[1]/a/@href')[0]
            time.sleep(0.1)
            f.write(f'{name},{fen},{num},{year},{country},{type},{website}')
            f.write('\r')
    time.sleep(0.1)
复制代码

 

效果展示:

posted on   明.Sir  阅读(45)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
历史上的今天:
2021-08-19 mariadb密码审计
2021-08-19 mariadb安装
2021-08-19 解决mariadb无密码登录问题
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示