【问题标题】:How to pass arguments between two spiders with scrapy callback如何使用scrapy回调在两个蜘蛛之间传递参数
【发布时间】:2018-07-15 07:53:15
【问题描述】:

我有两个scrapy,第一个抓取站点地图并提取网址并将其放入txt文件中,第二个读取并逐行抓取此网址。

我的代码如下:

class sitemapSpider(SitemapSpider):
    name = "filmnetmapSpider"
    sitemap_urls = ['http://filmnet.ir/sitemap.xml']
    sitemap_rules = [
    ('/series/', 'parse_item')
    ]
    storage_file = 'urls.txt'

    def parse_item(self, response):
         videoid = response.url

         with open(self.storage_file, 'a') as handle:
            yield handle.writelines(videoid + '\n')

第二只蜘蛛:

class filmnetSpider(scrapy.Spider):
      name = 'filmnetSpider'

    def start_requests(self):
        with open('urls.txt') as fp:
            for line in fp:
                yield Request(line.strip(), callback=self.parse_website)

    def parse_website(self, response):
        hxs = HtmlXPathSelector(response)
        url = hxs.xpath('//script[@type="application/ld+json"]/text()').extract()
        url = ast.literal_eval(json.dumps(url))
        url = url[1]
        obj = json.loads(url)
        poster = obj['image']
        name = obj['name']
        description = obj['description']

如何更改代码以删除对文件的读/写?

如何在其中使用回调?

注意:此代码不适用于一个scrapy spider;代码为:两个给定的scrapy + 波纹管代码,如doc中所说的示例

process = CrawlerProcess()
process.crawl(filmnetSpider)
process.crawl(sitemapSpider)
process.start()

【问题讨论】:

  • 你能把你在一只scrapy spider上试过的代码贴出来吗?
  • 感谢您的关注,问题已修改。
  • 这段代码不会在文本文件中写入任何内容,它只是从站点地图中提取网址。
  • 你说要删除对文件的读/写...所以代码不再使用文件并将url直接传递给回调...
  • 我有一个问题;那么你为什么在你的代码中使用'storage_file'呢?此代码是否会抓取 url 并提取请求的项目(如“图像”或“名称”)?

标签: python callback scrapy scrapy-spider


【解决方案1】:

这应该可行:

class sitemapSpider(SitemapSpider):
    name = "filmnetmapSpider"
    sitemap_urls = ['http://filmnet.ir/sitemap.xml']
    sitemap_rules = [
    ('/series/', 'parse_item')
    ]

    def parse_item(self, response):
         videoid = response.url
         yield Request(videoid, callback=self.parse_website)

    def parse_website(self, response):
        hxs = HtmlXPathSelector(response)
        url = hxs.xpath('//script[@type="application/ld+json"]/text()').extract()
        url = ast.literal_eval(json.dumps(url))
        url = url[1]
        obj = json.loads(url)
        poster = obj['image']
        name = obj['name']
        description = obj['description']

【讨论】:

  • 这对于来自站点地图的 urlsscrapy 可以(parse_item() 刚刚运行),但它不会在 parse_website() 中返回请求的项目,(这个函数它不会运行)
猜你喜欢
  • 1970-01-01
  • 2015-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多