基于字符串参数的 Scrapy XmlFeedSpider - 如何抑制自动请求

Scrapy XmlFeedSpider based on String Argument - How to Suppress Automatic Request

目标: 通过将响应作为参数传递来触发 XMLFeedSpider 的执行(即不需要 start_urls)。

示例命令:

scrapy crawl spider_name -a response_as_string="<xml><sometag>abc123</sometag></xml>"

示例蜘蛛:

class ExampleXmlSpider(XMLFeedSpider):

    name = "spider_name"
    itertag = 'sometag'

    def parse_node(self, response, node):
        response2 = XmlResponse(url="Some URL", body=self.response_as_string)
        ProcessResponse().get_data(response2)

    def __init__(self, response_as_string=''):
        self.response_as_string = response_as_string

问题:终端抱怨没有start_urls。如果我在 start_urls.

中包含 dummy.xml ,我只能使上述工作正常

例如

start_urls = ['file:///home/user/dummy.xml']

问题: 是否有一个完全由参数提供的响应驱动的 XMLFeedSpider(根据原始命令)?在这种情况下,我需要抑制 XMLFeedSpider 寻找 start_url 来执行请求的需要。

谢谢保罗,你说得很对。更新了下面的示例代码。我不再将 class 称为 XMLFeedSpider。 Python 脚本已更新为 "object" 类型的 class,能够将 url 和正文作为参数传递。

from scrapy.http import XmlResponse    

class ExampleXmlSpider(object):

        def __init__(self, response_url='', response_body=''):
            self. response_url = response_url
            self.response_body = response_body

        def run(self):
            response = XmlResponse(url=self.response_url, body=self.response_body)
            print response.url