【问题标题】:Pass Scrapy Spider a list of URLs to crawl via .txt file通过 .txt 文件向 Scrapy Spider 传递要抓取的 URL 列表
【发布时间】:2013-06-22 20:42:50
【问题描述】:

我对 Python 有点陌生,对 Scrapy 也很陌生。

我已经设置了一个蜘蛛来抓取和提取我需要的所有信息。但是,我需要将 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.

我做了一些研究,但一直空手而归。我见过这种类型的示例 (How to pass a user defined argument in scrapy spider),但我认为这不适用于传递文本文件。

【问题讨论】:

    标签: python web-scraping scrapy command-line-arguments scrapy-spider


    【解决方案1】:
    class MySpider(scrapy.Spider):
        name = 'nameofspider'
    
        def __init__(self, filename=None):
            if filename:
                with open('your_file.txt') as f:
                    self.start_urls = [url.strip() for url in f.readlines()]
    

    这将是您的代码。如果它们以行分隔,它将从 .txt 文件中获取 url,例如, 网址1 网址2 等等。

    在此之后运行命令-->

    scrapy crawl nameofspider -a filename=filename.txt
    

    假设你的文件名是'file.txt',然后,运行命令 -->

    scrapy crawl myspider -a filename=file.txt
    

    【讨论】:

      【解决方案2】:

      如果您的网址是行分隔的

      def get_urls(filename):
              f = open(filename).read().split()
              urls = []
              for i in f:
                      urls.append(i)
              return urls 
      

      那么这行代码会给你网址。

      【讨论】:

        【解决方案3】:

        使用-a 选项运行您的蜘蛛,例如:

        scrapy crawl myspider -a filename=text.txt
        

        然后在蜘蛛的__init__方法中读取文件并定义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()
        

        希望对您有所帮助。

        【讨论】:

          【解决方案4】:

          您可以简单地读入 .txt 文件:

          with open('your_file.txt') as f:
              start_urls = f.readlines()
          

          如果您以换行符结尾,请尝试:

          with open('your_file.txt') as f:
              start_urls = [url.strip() for url in f.readlines()]
          

          希望对你有帮助

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-01-09
            • 1970-01-01
            • 2020-10-03
            • 1970-01-01
            • 2013-02-12
            • 1970-01-01
            • 2015-09-13
            • 1970-01-01
            相关资源
            最近更新 更多