【问题标题】:Scrapy how to recursively run a spider with dynamic (variable) argument?Scrapy如何递归运行带有动态(变量)参数的蜘蛛?
【发布时间】:2017-04-09 09:47:53
【问题描述】:

我编写了一个全功能蜘蛛的代码,它接受一个参数date。这将在蜘蛛的每次迭代中发生变化。

为了测试目的,我创建了一个执行以下操作的 shell 脚本。

  1. 有一个点文件.date,格式为YYYY-MM-DD,脚本读取文件并将日期传递给蜘蛛。
  2. 一旦任务完成并将数据保存到 mysql,日期值会减少一天,并将其保存在文件中以供下一次迭代。

Shell 脚本

lastDate=$(cat .dailyScrapeDate)
echo "Last scraped Date : $lastDate"
nextDate=$(date -d "$lastDate -1 day" "+%Y-%m-%d")
echo "Next scraped Date : $nextDate"

echo "Launching Spider"
scrapy crawl dailyDataSpider -a date=$nextDate

echo "Writing scraped date ($nextDate) to dot file .dailyScrapeDate"
echo "$nextDate" > .dailyScrapeDate

现在我需要将其移至爬虫进程。那么我该如何进行呢?我需要创建一个独立的 python 文件并运行它吗?例如我创建了一个文件process.py

Python 脚本 process.py

​​>
from DailyDataSpider import DailyDataSpider
from scrapy.crawler import CrawlerProcess

process = CrawlerProcess()
process.crawl( DailyDataSpider, date=date ) # TODO: Read and pass date
process.start()
# Save date?

参数 date=date 已通过,但我对如何在此之后继续前进感到有些困惑。我是否在 python 文件上读取和写入点文件?这个文件代码是在每次迭代时运行还是废弃只接受一次参数并使用它运行?

问题:如何递归运行带有动态(变量)参数的蜘蛛?

【问题讨论】:

    标签: python scrapy web-crawler twisted scrapy-spider


    【解决方案1】:

    这个脚本没问题

    from DailyDataSpider import DailyDataSpider
    from scrapy.crawler import CrawlerProcess
    
    process = CrawlerProcess()
    process.crawl( DailyDataSpider, date=date ) # TODO: Read and pass date
    process.start()
    

    现在在您的蜘蛛文件中执行此操作

    from scrapy.spiders import CrawlSpider
    class DailyDataSpider (CrawlSpider):
    
          def __init__(self, date=None):
                 if date:
                      self.date = date
    

    现在可以在蜘蛛的任何位置访问self.date。 你可以在pipelinemiddleware 中访问date,比如spider.date

    init() 中提供默认 None 以防止在我们不想传递日期参数时出现错误...所以 scrapy crawl spider1 -a date=date_herescrapy crawl spider1 可以工作

    【讨论】:

    • 可能应该总是分配self.date。我不确定为什么这里提供了默认的None,但如果它有用,那么让下游应用程序代码检查它 - 而不是在未设置时遇到 AttributeError。
    • @Jean-PaulCalderone Default None 在 __init__() 中提供以防止在我们不想传递日期参数时出现错误......所以 scrapy crawl spider1 -a date=date_herescrapy crawl spider1 可以工作
    • 如果应用程序代码需要一个日期来运行,那么进程在scrapy crawl ...时间失败要比在稍后的某个随机时间点失败要好得多爬行。但是,可以肯定的是,保留默认值并无条件地创建属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 2016-01-12
    • 1970-01-01
    • 2015-09-08
    • 2018-12-23
    • 1970-01-01
    相关资源
    最近更新 更多