搜索加载了 JS 的项目时,Scrapy 飞溅无法正常工作

Nic*_*les 5 python lua scrapy web-scraping scrapy-splash

我正在使用带有scrapy splash 的scrapy 从一些URL 获取数据,例如这个产品url或这个产品url 2

我有一个等待时间的 Lua 脚本并返回 HTML:

script = """
            function main(splash)
              assert(splash:go(splash.args.url))
              assert(splash:wait(4))
              return splash:html()
            end
"""
Run Code Online (Sandbox Code Playgroud)

然后我执行它。

yield SplashRequest(url, self.parse_item, args={'lua_source': script},endpoint='execute')
Run Code Online (Sandbox Code Playgroud)

从这里我需要 3 个元素,它们是 3 种不同的产品价格。这 3 种都加载了 JS。

价格

我有 xpath 来获取 3 个元素。但问题是有时行得通有时行不通

    price_strikethrough = response.xpath('//div[@class="price-selector"]/div[@class="prices"]/span[contains(@class,"active-price strikethrough")]/span[1]/text()').extract_first() 
    price_offer1 = response.xpath('//div[@class="price-selector"]/div[@class="prices"]/div[contains(@class,"precioDescuento")][1]/text()').extract_first()
    price_offer2 = response.xpath('//div[@class="price-selector"]/div[@class="prices"]/div[contains(@class,"precioDescuento")][2]/text()').extract_first()
Run Code Online (Sandbox Code Playgroud)

我不知道还能做些什么才能使其正常工作。我曾尝试更改等待值,但结果相同。有时它工作正常,有时我没有得到数据。我怎样才能确保我总能得到我需要的数据?

小智 0

你的方法没有问题,但问题似乎出在网站上。网站计算价格的时间是可变的,您需要更新时间,时间lua_script应该在 7 到 8 秒左右。