Scrapy read list of URLs from file to scrape?

后端 未结 3 1731
执念已碎
执念已碎 2020-12-23 18:16

I\'ve just installed scrapy and followed their simple dmoz tutorial which works. I just looked up basic file handling for python and tried to get the crawler to read a list

3条回答
  •  轮回少年
    2020-12-23 18:51

    Arise with similar question when writing my Scrapy helloworld. Beside reading urls from a file, you might also need to input file name as an argument. This can be done by the Spider argument mechanism.

    My example:

    class MySpider(scrapy.Spider):                                                
        name = 'my'                                                               
        def __init__(self, config_file = None, *args, **kwargs):                    
            super(MySpider, self).__init__(*args, **kwargs)                       
            with open(config_file) as f:                                            
                self._config = json.load(f)                                         
            self._url_list = self._config['url_list']                             
    
        def start_requests(self):                                                   
            for url in self._url_list:                                              
                yield scrapy.Request(url = url, callback = self.parse)              
    

提交回复
热议问题