我正试图从电子商务网站上为某一特定产品刮取数据。在结果页面上,列出了50种产品。有些产品有它们的原价,而有些产品的折扣价格与原来的价格脱节。它的HTML代码是
非折扣产品
<div class="class-1">
<span>
Rs. 7999
</span>
</div>贴现产品
<div class="class-1">
<span>
<span class="class-2">
Rs. 11621
</span>
<span class="class-3">
Rs. 15495
</span>
</span>
<span class="class-4">
(25% OFF)
</span>
</div>结果应该是什么?
我想要一个代码,可以滚动产品列表,从Div[class='class-1]/span标签中提取非折扣产品的数据,如果存在子span[class='class-2'],它应该只从该标签中提取数据,而不是从Span[Class-3]标记中提取数据。救命啊!!
发布于 2021-05-21 07:26:04
如果我明白你的意思,首先你需要得到一份产品清单,上面有:
products = driver.find_element_by_xpath('//div[@class="class-1"]')现在,您可以遍历产品列表,并按以下方式获取价格
prices = []
for product in products:
discount_price = product.find_elements_by_xpath('.//span[@class="class-2"]')
if(discount_price):
prices.append(discount_price[0].text)
else:
prices.append(product.find_element_by_xpath('./span').text)解释:
在每个产品中,我都要检查您定义的//span[@class="class-2"]子元素的存在。如果有这样的元素,product.find_elements_by_xpath('.//span[@class="class-2"]')将返回非空的web元素列表。在Python中,不是空列表是布尔True,所以if会消失。
否则,列表是空的,else就会消失。
https://stackoverflow.com/questions/67632328
复制相似问题