繁体   English   中英

如何循环遍历多个 URL 以从 Scrapy 中的 CSV 文件中抓取?

[英]How to loop through multiple URLs to scrape from a CSV file in Scrapy?

我从阿里巴巴网站抓取数据的代码:

import scrapy




class IndiamartSpider(scrapy.Spider):
    name = 'alibot'
    allowed_domains = ['alibaba.com']
    start_urls = ['https://www.alibaba.com/showroom/acrylic-wine-box_4.html']


    def parse(self, response):
        Title = response.xpath('//*[@class="title three-line"]/a/@title').extract()
        Price = response.xpath('//div[@class="price"]/b/text()').extract()
        Min_order = response.xpath('//div[@class="min-order"]/b/text()').extract()
        Response_rate = response.xpath('//i[@class="ui2-icon ui2-icon-skip"]/text()').extract()

        for item in zip(Title,Price,Min_order,Response_rate):
            scraped_info = {
                'Title':item[0],
                'Price': item[1],
                'Min_order':item[2],
                'Response_rate':item[3]

            }
            yield scraped_info

注意起始 url,它只抓取给定的 URL,但我希望此代码抓取我的 csv 文件中存在的所有 url。 我的 csv 文件包含大量 URL。 data.csv 文件示例::

'https://www.alibaba.com/showroom/shock-absorber.html',
'https://www.alibaba.com/showroom/shock-wheel.html',
'https://www.alibaba.com/showroom/shoes-fastener.html',
'https://www.alibaba.com/showroom/shoes-women.html',
'https://www.alibaba.com/showroom/shoes.html',
'https://www.alibaba.com/showroom/shoulder-long-strip-bag.html',
'https://www.alibaba.com/showroom/shower-hair-band.html',
...........

我如何一次导入代码中的所有 csv 文件链接?

要正确循环文件而不将所有文件加载到内存中,您应该使用生成器,因为 python/scrapy 中的文件对象和 start_requests 方法都是生成器:

class MySpider(Spider):
    name = 'csv'

    def start_requests(self):
        with open('file.csv') as f:
            for line in f:
                if not line.strip():
                    continue
                yield Request(line)

进一步解释:Scrapy 引擎使用start_requests生成请求。 它将继续生成请求,直到并发请求限制已满(设置如CONCURRENT_REQUESTS )。
还值得注意的是,默认情况下,scrapy 爬行深度优先 - 较新的请求优先,因此 start_requests 循环将最后完成。

你快到了。 唯一的变化是在start_urls ,您希望它成为“*.csv 文件中的所有 url”。 以下代码可轻松实现该更改。

with open('data.csv') as file:
    start_urls = [line.strip() for line in file]

让我们假设您已经以数据帧的形式存储了 url 列表,并且您想要遍历数据帧中存在的每个 URL。 下面给出了我的方法,它对我有用。

class IndiamartSpider(scrapy.Spider):
    name = 'alibot'
    #allowed_domains = ['alibaba.com']
    #start_urls = ['https://www.alibaba.com/showroom/acrylic-wine-box_4.html']
    

    def start_requests(self):
        df = pd.read_csv('fileContainingUrls.csv')
        #Here fileContainingUrls.csv is a csv file which has a column named as 'URLS'
        # contains all the urls which you want to loop over. 
        urlList = df['URLS'].to_list()
        for i in urlList:
             yield scrapy.Request(url = i, callback=self.parse)

    def parse(self, response):
       Title = response.xpath('//*[@class="title three-line"]/a/@title').extract()
       Price = response.xpath('//div[@class="price"]/b/text()').extract()
       Min_order = response.xpath('//div[@class="min-order"]/b/text()').extract()
    
       for item in zip(Title,Price,Min_order,Response_rate):
           scraped_info = {
               'Title':item[0],
               'Price': item[1],
               'Min_order':item[2],
               'Response_rate':item[3]

           }
           yield scraped_info

  

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM