python - 使用 xpath 选择 html 属性的不同值
问题描述
我需要从这个代码中选择reference
值和其他一些值(例如) (或者如果它更好)。delivery_out_of_stock
xpath
css
关于如何处理它的任何建议?
<div class="tab-pane" id="product-details" data-product="{"id_shop_default":"1","id_manufacturer":"993","id_supplier":"0","reference":"0165926","is_virtual":"0","delivery_in_stock":"","delivery_out_stock":"","id_category_default":"1006","on_sale":"0","online_only":"0","ecotax":0,"minimal_quantity":"1","low_stock_threshold":null}" role="tabpanel">
</div>
解决方案
我会使用 xpath 来获取数据产品中的数据,然后将 json 作为字典加载以查找所需的值:
import json
# xpath to get the data in data-product
data_product = response.xpath('//*[@id="product-details"]/@data-product').extract_first()
# load the json in a dictionary
data = json.loads(data_product)
# get the value by key
reference = data['refererce']
delivery_out_of_stock = data['delivery_out_of_stock']
推荐阅读
- python - Convert Variable Type from DataFrame to DatetimeIndex
- c# - Multiple foreign keys pointing to same navigational property
- json - 检查 JSON 响应中是否存在关键字 - Azure 逻辑应用
- javascript - Value in loop doesn't subtract
- amazon-web-services - 如何使用 OpenAPI 为 AWS API Gateway 配置 CORS?
- mysql - mysql存储过程,选择最大值并插入值并分配给变量
- angular - 版本 10 上的 Angular 材料日期选择器(日期范围功能)
- node.js - 关闭终端或控制台后永远无法正常工作
- javascript - 如何在 React 中为嵌套对象设置状态?
- android - 更新到 gradle 6.x variant.getVariantData().getVariantConfiguration() 后,Gradle 代码损坏