首页 > 解决方案 > 当父标签仅对某些元素有子标签时抓取数据

问题描述

我正在尝试从电子商务网站上抓取特定产品的数据。在结果页面上,列出了 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]标签中提取数据。请帮忙!!

标签: python-3.xselenium

解决方案


如果我清楚地了解您,首先您需要获取以下产品列表:

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 元素列表。非空列表True在 Python 中是布尔值,所以if会去。
否则列表为空并且else会消失。


推荐阅读