python - 搜索加载了 JS 的项目时,Scrapy splash 无法正常工作
问题描述
我正在使用带有 scrapy splash 的 scrapy 从某些 URL 获取数据,例如 this product url或 this product url 2。
我有一个等待时间的 Lua 脚本并返回 HTML:
script = """
function main(splash)
assert(splash:go(splash.args.url))
assert(splash:wait(4))
return splash:html()
end
"""
然后我执行它。
yield SplashRequest(url, self.parse_item, args={'lua_source': script},endpoint='execute')
从这里我需要 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()
我不知道还要做什么才能使其正常工作。我试过改变等待值,但它是一样的。有时它工作正常,有时我没有得到数据。我如何确保始终获得所需的数据?
解决方案
您的方法没有任何问题,但问题似乎出在网站上。网站计算价格需要不同的时间,您需要更新您的时间,lua_script
它应该在 7 到 8 秒左右。