Scrapy XmlFeedSpider基于String Argument - 如何抑制自动请求

时间:2016-06-05 09:57:50

标签: python scrapy scrapy-spider

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

示例命令:

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,我只能使上述工作正常工作。

E.g。

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

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

1 个答案:

答案 0 :(得分:0)

谢谢保罗,你是当之无愧的。更新了以下示例代码。我不再将该类称为XMLFeedSpider。 Python脚本更新为类型&#34;对象&#34;能够将url和body作为参数传递。

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