如何在selenium python中获取html5 dataattribute的值

2024-10-01 07:45:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从"value":"165796011"中获取值,它位于data-gbfilter-checkbox

我曾经

element= driver.find_element_by_css_selector('#widgetFilters > div:nth-child(1) > div.a-row.a-expander-container.a-expander-inline-container > span:nth-child(3)')
print(element.get_attribute('data-gbfilter-checkbox'))

但是它给了我所有在data-gbfilter-checkbox苞片之间的数据

HTML:

<span class="a-declarative" data-action="gbfilter-checkbox" data-gbfilter-checkbox="
{"attribute":"whitelist_categories","value":"165796011","rangeEnd":"","rangeStart":"","filterType":"checkboxes"}">
</span>

我解决了,但现在(我不想写7,我想用动态的方式)

很好,我将字符串转换为列表和值7,但这是我希望通过动态方式查找数字的静态方式(我不想写7,我希望使用动态方式)

 pages= driver.find_element_by_css_selector('#widgetFilters > div:nth-child(1) > div.a-row.a-expander-container.a-expander-inline-container > div > span:nth-child(25)')

 list= pages.get_attribute('data-gbfilter-checkbox').split('"') print(list[7])

Tags: divchilddatavaluecontainerdriver方式动态
1条回答
网友
1楼 · 发布于 2024-10-01 07:45:21

您可以将其解析为json,然后引用该字段:

import json
json = json.loads(pages.get_attribute('data-gbfilter-checkbox'))

# the result is a Python dictionary:
print(json["value"])

相关问题 更多 >