我正在尝试使用Scrapy爬行一系列的游戏商店,并且都遇到了相同的问题。我使用的是XPath,游戏价格的超文本标记语言会根据价格是简单地标记为£ 20.09,还是标记为£ 20.09,然后用£ 14.49来显示折扣。我很高兴有两列,was 20.09 (将包含空值)和now 14.49之后的一列,但我不知道如何使用空值来代替它,只是替换了下面所有的空值。
这是我的代码为网站cdkeys https://www.cdkeys.com/pc/games?limit=50,其中有两个游戏有和没有折扣。
allowed_urls = ['https://www.cdkeys.com/pc/games?limit=50?']
start_urls = ['https://www.cdkeys.com/pc/games/{pageno}?limit=50'.format(pageno=pageno)
for pageno in range(1, 10)]
def parse(self, response):
Games = response.xpath('//*[@id="root-wrapper"]/div/div[1]/div[2]/div[3]/div[2]/div[2]/ul/li/h2/a/text()').extract()
Prices = response.xpath('//span[starts-with(@id, "product-price-")]/span[1]/span/text()').extract()
for i, (Game, Price) in enumerate(zip(Games, Prices)):
yield {'index': i, 'Game': Game, 'Price':Price}这个问题存在于价格的XPath中,我可以得到只有折扣价格的列表,或者只有没有折扣的游戏的价格列表,因为这些类别的超文本标记语言是完全不同的。
阻止我简单地创建两个列表的是,因为我使用的是zip和enumerate,所以它只是简单地迭代第一个x数量的游戏,直到它的价格用完,而不是将每个游戏链接到相应的价格。
无论是在Prices中只显示正确的价格,还是找到一种具有空值而不是替换以下值的方法,任何帮助都将非常感谢。我对python和web爬虫都是新手,我只是想弄明白这一切。
发布于 2018-01-07 01:31:06
我会采取不同的方式--逐个迭代产品项目,然后找到游戏名称、常规价格和折扣价格:
def parse(self, response):
for game in response.css("ul.products-grid li.item"):
name = game.css("h2.product-name > a::text").extract_first()
old_price = game.css(".regular-price .price::text,.old-price .price::text").extract_first()
discount_price = game.css(".special-price .price::text").extract_first()
yield {
"name": name,
"old_price": old_price,
"discount_price": discount_price
}对于第一页,您将获得以下输出:
{'old_price': u'$ 13.59', 'name': u'Stellaris: Utopia PC DLC', 'discount_price': None}
{'old_price': u' $ 9.49 ', 'name': u'Insurgency PC', 'discount_price': u' $ 1.99 '}
...
{'old_price': u' $ 81.59 ', 'name': u'Call of Duty Black Ops II 2 Digital Deluxe Edition PC ', 'discount_price': u' $ 13.59 '}请注意旧价格是如何填写的,包括折扣和没有折扣。
https://stackoverflow.com/questions/48129892
复制相似问题