You need to enable JavaScript to run this app. Scrapy爬取雅虎财经时报模糊错误 无法获取市场指数收盘价
优惠活动
大模型
产品
解决方案
定价
更多

Scrapy爬取雅虎财经时报模糊错误 无法获取市场指数收盘价

问题排查及修复方案

核心错误点

  • start_requests方法未yield请求:你当前在start_requests里仅创建了Request对象,没有通过yield返回,导致Scrapy根本不会发送首页请求,自然没有后续抓取逻辑
  • process.crawl传参错误:你的YahooFinanceSpider自定义构造函数要求传入urls参数,但调用process.crawl时仅传入了爬虫类,没有携带urls参数,同时你提前实例化的yscraper对象没有被使用
  • 默认User-Agent被反爬拦截:Scrapy默认的User-Agent会被雅虎财经识别为爬虫,直接拒绝访问,不会返回正常页面内容
  • 选择器冗余问题:你先用xpath选中a标签后再用css取href属性,写法冗余,且雅虎的前端类名是动态生成的,很容易失效导致匹配不到元素

修复后可运行代码

import scrapy
from scrapy.crawler import CrawlerProcess

class YahooFinanceSpider(scrapy.Spider):
    name = "yahoo_stock_scraper"
    # 直接定位市场指数链接的href,避免依赖易变的动态类名
    index_link_loc = '//div[contains(@id,"marketsummary-itm")]/h3/a/@href'
    # 收盘价定位适当放宽匹配规则,避免绝对路径变动失效
    close_loc = '//div[@id="quote-summary"]//tr[contains(.,"Previous Close")]/td[2]/span/text()'

    def __init__(self, urls=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.urls = urls or []

    def start_requests(self):
        for url in self.urls:
            # 必须yield请求才会被Scrapy调度执行
            yield scrapy.Request(url=url, callback=self.parse_front)

    def parse_front(self, response):
        # 直接提取所有市场指数链接
        links_to_follow = response.xpath(self.index_link_loc).extract()
        for url in links_to_follow:
            yield response.follow(url=url, callback=self.parse_pages)

    def parse_pages(self, response):
        closing_value = response.xpath(self.close_loc).extract_first()
        if closing_value:
            print(f"最新收盘价:{closing_value}")
        else:
            # 增加调试输出方便排查选择器适配问题
            print(f"页面{response.url}未匹配到收盘价")


if __name__ == "__main__":
    urls = ['https://finance.yahoo.com/']
    # 配置浏览器UA绕过基础反爬检测
    process = CrawlerProcess(settings={
        "USER_AGENT": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"
    })
    # 传入爬虫类和必要的初始化参数
    process.crawl(YahooFinanceSpider, urls=urls)
    process.start()

验证说明

运行修复后的代码,你会先看到Scrapy启动日志,随后会输出每个市场指数页面对应的收盘价,若未匹配到对应值也会输出对应页面URL,你可以根据当前雅虎财经的页面结构微调选择器即可适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 05:54:04