python-3.x - 当父标签仅对某些元素有子标签时抓取数据
问题描述
我正在尝试从电子商务网站上抓取特定产品的数据。在结果页面上,列出了 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]
标签中提取数据。请帮忙!!
解决方案
如果我清楚地了解您,首先您需要获取以下产品列表:
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
会消失。
推荐阅读
- ios - 如何将 activityIndicator 置于其超级视图的中心?
- sql-server - 输出包含多个数组的 JSON
- dm-script - DigitalMicrograph 光束移位脚本
- unit-testing - 下载 github 项目的 zip 时单元测试不会运行,但从命令行克隆时可以正常工作
- delphi - 在 TForm2 的 OnClose 时简单启用 TForm1 的 TButton
- reactjs - 如何使用react js构建动态项目集乘以3
- sql - 将 nvarchar 值“H14”转换为数据类型 int 时转换失败
- r - 您如何在 [r] 中编写多个栅格?
- python - 如何使用 mibdump.py 生成不同名称的 pysnmp MIB?
- java - 找到多个文件,其独立于操作系统的路径为“convertGermanToBoolean.properties”