小编典典

向Scrapy Spider传递URL列表以通过.txt文件进行抓取

scrapy

我是Python的新手,也是Scrapy的新手。

我已经设置了一个spider来爬行和提取我需要的所有信息。但是,我需要将URL的.txt文件传递给start_urls变量。

例如:

class LinkChecker(BaseSpider):
    name = 'linkchecker'
    start_urls = [] #Here I want the list to start crawling a list of urls from a text file a pass via the command line.

我做了一些研究,并空手而归。我已经看到了这种类型的示例(如何在scrapy spider中传递用户定义的参数),但是我认为这不适用于传递文本文件。


阅读 972

收藏
2020-04-09

共1个答案

小编典典

使用以下-a选项运行你的spider:

scrapy crawl myspider -a filename=text.txt

然后__init__使用Spider方法读取文件并定义start_urls

class MySpider(BaseSpider):
    name = 'myspider'

    def __init__(self, filename=None):
        if filename:
            with open(filename, 'r') as f:
                self.start_urls = f.readlines()

希望能有所帮助。

2020-04-09