You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Scrapy爬取Newegg笔记本数据遇302重定向,无法提取数据求助

问题分析与解决方案

核心问题排查

从日志和代码来看,三个关键错误导致无法提取数据:

  1. 重定向被阻断:请求返回302状态码,但你设置了REDIRECT_ENABLED=False,Scrapy未跟进重定向,拿到的不是包含笔记本数据的实际页面。
  2. 请求头错误:配置的headers属于其他网站,与Newegg站点不匹配,会被服务器识别为异常请求。
  3. 选择器逻辑错误:屏幕尺寸所在的td和标题所在的td.td-item是同一<tr>下的同级节点,从td-item内部查找Screen Size的内容必然失败。

修正步骤

1. 恢复重定向处理

移除custom_settings = {'REDIRECT_ENABLED': False}和handle_httpstatus_list = [302],让Scrapy自动跟进重定向,获取目标页面内容。

2. 使用适配的请求头

替换为符合Newegg访问规则的请求头,核心保留User-Agent即可,避免使用无关网站的头信息。

3. 修正选择器逻辑

遍历每台笔记本所在的<tr>行,从行内分别提取标题和屏幕尺寸:

  • 标题:从行内的.goods-title-content节点提取
  • 屏幕尺寸:从行内包含hid-text文本为Screen Size的td-spec节点下的span提取

修正后的完整代码

import scrapy

class LaptopSpider(scrapy.Spider):
    name = "laptop"
    # 适配Newegg的请求头
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36"
    }
    start_urls = ['https://www.newegg.com/tools/laptop-finder']

    def start_requests(self):
        for url in self.start_urls:
            yield scrapy.Request(url, headers=self.headers)

    def parse(self, response):
        # 遍历每台笔记本对应的tr行
        for product_row in response.css('tr'):
            # 提取标题
            title = product_row.css('.goods-title-content::text').get()
            # 提取屏幕尺寸:定位到包含"Screen Size"的td-spec节点,再取后续span文本
            screen_size = product_row.xpath('.//td[contains(@class, "td-spec")]/div[text()="Screen Size"]/following-sibling::span/text()').get()
            
            # 过滤空数据,仅输出有效条目
            if title and screen_size:
                yield {
                    'Title': title.strip(),
                    'Screen Size': screen_size.strip()
                }

额外提示

  • 调试阶段可使用scrapy shell https://www.newegg.com/tools/laptop-finder测试选择器,验证能定位元素后再写入代码。
  • 若遇到反爬限制,可在custom_settings中添加DOWNLOAD_DELAY = 2降低请求频率。

内容的提问来源于stack exchange,提问作者AyushD95

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 05:00:54