Vincent Vincent - 3 months ago 9
JSON Question

Selenium Python : extract field from json data in <a> tag

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 ?

Answer

you use get_attribute and json convertion:

>>> import json
>>> data = browser.findElement(By.XATH(".//*[@id='AAA']").get_attribute("data-json")
>>> json.loads(data)["field2"]
>>> 5
Comments