【问题标题】:Scrapy runspider / how to use different settings?Scrapy runspider / 如何使用不同的设置?
【发布时间】:2022-01-17 04:44:30
【问题描述】:

我有以下工作蜘蛛作为一个进程 - 所以我可以使用以下命令启动蜘蛛:python xyz.py

import scrapy
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings

class onlyLinks(scrapy.Spider):
  name = 'onlyLinks'
  allowed_domains = ['magnatiles.com']
  start_urls = ['https://www.magnatiles.com/products/page/1/']

  def parse(self, response):
    tmpProd = response.xpath("//ul[@class='products']//ancestor::li")
    for p in tmpProd:
      yield {
        "link": p.xpath("(./a)[1]/@href").get(),
        "name": p.xpath(".//h2/text()").get(),
        "sku": p.css("a.button::attr(data-product_sku)").get(),
        "price": p.xpath("//span[@class='price']//ancestor::bdi/text()").get()
      }

process = CrawlerProcess(settings={
  "FEEDS": {
      "items.json": {"format": "json"},
      # "items.csv": {"format": "csv"},
      # "items.xlsx": {"format": "xlsx"},
  },
})

process.crawl(onlyLinks)
process.start()

但是我如何使用 settings.py 中的其他信息/设置? 例如。 ROBOTSTXT_OBEY = False,AUTOTHROTTLE_ENABLED = True,AUTOTHROTTLE_START_DELAY = 5 等等。

我怎样才能以这种方式输出到 json - 所以输出会被覆盖? (当我现在运行程序时,数据总是附加到现有的 items.json 文件中) (当我用 scrapy runpider 运行蜘蛛时,我会使用 -o 或 -O 来覆盖或不覆盖输出文件 - 但我该怎么做呢?)

【问题讨论】:

    标签: python web-scraping scrapy


    【解决方案1】:

    您可以使用表示dict 格式的键值对来执行此操作,如下所示:

    process = CrawlerProcess ({
        "FEEDS": {"items.json": {"format": "json", "overwrite": True}},
        'ROBOTSTXT_OBEY':'False',
        'USER_AGENT': 'Mozilla/5.0',
        'AUTOTHROTTLE_ENABLED':'True',
        'AUTOTHROTTLE_START_DELAY': '5'
        })
    
    process.crawl(onlyLinks)
    process.start()
    

    【讨论】:

    • 好的,谢谢 - 但是如何设置是否覆盖 json?
    • 其实scrapy doc没有设置覆盖json
    • 我已经对解决方案进行了编辑,以向您展示如何覆盖文件。
    • 使用新参数效果很好 - thx
    猜你喜欢
    • 2021-01-21
    • 2013-10-20
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多