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

使用Scrapy CrawlSpider遇TypeError:'Rule'对象不可迭代问题求助

问题解决:TypeError: 'Rule' object is not iterable

错误出在rules的定义上。当你用元组包裹单个Rule对象时,必须在元素末尾添加逗号,否则Python会将其解析为单个Rule实例,而非可迭代的元组类型,这就导致了报错。

修正后的代码如下:

import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor


class DogstatsSpider(CrawlSpider):
    name = "dogstats"
    allowed_domains = ["www.ukdogracing.net"]
    start_urls = ["http://www.ukdogracing.net/todays-runners/"]
    
    rules = (
        Rule(LinkExtractor(allow='runners'), callback='parse_item'),  # 添加逗号,明确这是元组
    )

    def parse_item(self, response):
        
        yield {
            'dogtime' : "test"
        }

你也可以改用列表来定义rules,这样就不需要额外加逗号:

rules = [
    Rule(LinkExtractor(allow='runners'), callback='parse_item')
]

CrawlSpider要求rules必须是包含Rule对象的可迭代结构(元组或列表),只要满足这个要求就能解决该错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 18:28:13