将Scrapy Spider传递给要通过.txt文件进行爬网的URL列表

clo*_*d36 3 python command-line-arguments scrapy web-scraping scrapy-spider

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

我已经设置了一个蜘蛛来抓取并提取我需要的所有信息.但是,我需要将.txt文件的URL传递给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.
Run Code Online (Sandbox Code Playgroud)

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

ale*_*cxe 16

使用以下-a选项运行您的蜘蛛:

scrapy crawl myspider -a filename=text.txt
Run Code Online (Sandbox Code Playgroud)

然后__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()
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.