Web scraping 用刮痧换网站发国家

Web scraping 用刮痧换网站发国家,web-scraping,scrapy,Web Scraping,Scrapy,我需要清理网站 选择一个不同的国家,所有的价格都会发生变化。名单上有40多个国家,每个国家都必须报废 我现在的蜘蛛很简单 # coding=utf-8 import scrapy class BlogSpider(scrapy.Spider): name = 'blogspider' start_urls = ['http://www.yellowkorner.com/photos/index.aspx'] def parse(self, response):

我需要清理网站 选择一个不同的国家,所有的价格都会发生变化。名单上有40多个国家,每个国家都必须报废

我现在的蜘蛛很简单

# coding=utf-8

import scrapy


class BlogSpider(scrapy.Spider):
    name = 'blogspider'
    start_urls = ['http://www.yellowkorner.com/photos/index.aspx']

    def parse(self, response):
        for url in response.css('a::attr("href")').re(r'/photos/\d\d\d\d/.*$'):
            yield scrapy.Request(response.urljoin(url), self.parse_prices)

    def parse_prices(self, response):
        yield None
如何获取所有国家/地区的价格信息


用firebug打开页面并刷新。在面板网络/子面板Cookie上查看网页,您将看到该页面使用Cookie保存国家信息(参见下图)

因此,您必须在请求时强制cookie“YellowKornerCulture”属性值LANGUAGE和COUNTRY。我根据您的代码制作了一个示例,以获取站点上可用的国家/地区,并通过一个循环获取所有价格。请参阅下面的代码:

# coding=utf-8

import scrapy


class BlogSpider(scrapy.Spider):
    name = 'blogspider'
    start_urls = ['http://www.yellowkorner.com/photos/index.aspx']

    def parse(self, response):
        countries = self.get_countries(response)
    #countries = ['BR', 'US'] try this if you only have some countries     
    for country in countries:
        #With the expression re(r'/photos/\d\d\d\d/.*$') you only get photos with 4-digit ids. I think this is not your goal.   
            for url in response.css('a::attr("href")').re(r'/photos/\d\d\d\d/.*$'):
                yield scrapy.Request(response.urljoin(url), cookies={'YellowKornerCulture' : 'Language=US&Country='+str(country), 'YellowKornerHistory' : '', 'ASP.NET_SessionId' : ''}, callback=self.parse_prices, dont_filter=True, meta={'country':country})

    def parse_prices(self, response):
        yield {
        'name': response.xpath('//h1[@itemprop="name"]/text()').extract()[0],   
        'price': response.xpath('//span[@itemprop="price"]/text()').extract()[0],
        'country': response.meta['country']

    }
    #function that gets the countries avaliables on the site    
    def get_countries(self, response):
        return response.xpath('//select[@id="ctl00_languageSelection_ddlCountry"]/option/attribute::value').extract()
花了一定的时间来解决这个问题,但是您必须删除站点用于选择语言页面的另一个cookie。我还将语言值固定为英语(美国)。之所以使用参数
dont\u filter=True
,是因为您在每次循环迭代中都会请求一个已请求的url,而scrapy的默认行为是由于性能原因,不重复对同一url的请求

PS:提供的xpath表达式可以改进


希望这能有所帮助。

分享你所做的一切。这不是一个棘手的问题,你应该在更改国家/地区时检查正在执行哪些请求,使用类似于
firebug
的方法调试请求。谢谢你的详细解释,这对我帮助很大。