wjwdxy123 2025-11-01 09:27 采纳率: 0%
浏览 7

爬虫爬取豆瓣电影top250

为何我写的爬虫爬取豆瓣top250个电影,他重复爬了前25个电影10

def get_first_text(data_list):
        try:
            return data_list[0].strip()
        except:
            return "未获取到数据"
urls=['https://movie.douban.com/top250?start={i*25}&filter=' for i in range(10)]
count=1
for url in urls:
    print(f"爬取:{url}")
    res=requests.get(url=url,headers=headers,timeout=10)
    print(res.status_code)
    html=etree.HTML(res.text)
    lis=html.xpath('//*[@id="content"]/div/div[1]/ol/li')
    print(len(lis))

    for li in lis:
        title=get_first_text(li.xpath('./div/div[2]/div[1]/a/span[1]/text()'))
        src=get_first_text(li.xpath('./div/div[2]/div[1]/a/@href'))
        director=get_first_text(li.xpath('./div/div[2]/div[2]/p[1]/text()'))
        score=get_first_text(li.xpath('./div/div[2]/div[2]/div/span[2]/text()'))
        comment=get_first_text(li.xpath('./div/div[2]/div[2]/div/span[4]/text()'))
        summary=get_first_text(li.xpath('./div/div[2]/div[2]/p[2]/span/text()'))
  • 写回答

4条回答 默认 最新

  • 阿里嘎多学长 2025-11-01 09:36
    关注

    阿里嘎多学长整理AIGC生成,因移动端显示问题导致当前答案未能完全显示,请使用PC端查看更加详细的解答过程

    问题分析

    你正在尝试爬取豆瓣电影top250的数据,但发现爬虫重复爬取了前25个电影的数据。

    解决方案

    可能的原因是豆瓣网站对爬虫有反爬虫机制,或者是你的爬虫代码有问题。以下是一些可能的解决方案:

    1. 检查爬虫代码: 确保你的爬虫代码正确地解析了豆瓣网站的HTML结构,避免了重复爬取数据。
    2. 使用代理: 使用代理服务器来访问豆瓣网站,避免被反爬虫机制检测到。
    3. 增加睡眠时间: 在爬取数据之间增加睡眠时间,避免被反爬虫机制检测到。
    4. 使用更好的爬虫库: 使用更好的爬虫库,如Scrapy,来爬取数据。

    核心代码

    import requests
    from bs4 import BeautifulSoup
    
    def get_douban_top250():
        url = 'https://movie.douban.com/top250'
        headers = {'User-Agent': 'Mozilla/5.0'}
        response = requests.get(url, headers=headers)
        soup = BeautifulSoup(response.content, 'html.parser')
        # 解析数据
        data_list = soup.find_all('div', class_='item')
        # 处理数据
        for data in data_list:
            # ...
        return data_list
    
    # 使用代理
    proxies = {'http': 'http://your_proxy:your_password@your_proxy_ip:your_proxy_port'}
    response = requests.get(url, headers=headers, proxies=proxies)
    

    注意: 这个代码片段是为了示例目的,需要根据实际情况进行调整。

    评论

报告相同问题?

问题事件

  • 创建了问题 11月1日