On a particular webpage, I have the following tag :
<a id="AAA" class="BBB" data-json="{"link":"thelink","field1":1,"field2":5}">
Load more
</a>
I am using Selenium / Python. I want to click 5 times on this tag, where 5 is the value from "field2" in "data-json".
The XPATH is ".//*[@id='AAA']" (thanks to FireXPath) so I want to use 5 times the following command:
browser.findElement(By.XATH(".//*[@id='AAA']")).click();
Question is : how to extract this "5" from < a tag > / data-json / field2 ?
答案 0 :(得分:1)
要获取属性的值,可以使用函数get_attribute
link,在这种特殊情况下,我们必须将data-json解析为dict并获取数字。我的建议是:
import json
json_dict = json.loads(browser.findElement(By.ID('AAA')).get_attribute('data-json'))
number_times = json_dict["field2"]
答案 1 :(得分:0)
正如同行所提到的,使用 id 会好得多。
您可以使用get_attribute
和json convertion:
>>> import json
>>> data = browser.find_element_by_id("AAA").get_attribute("data-json")
>>> json.loads(data)["field2"]
>>> 5