Search code examples
pythonseleniumxpathuniqueidentifier

How to retrieve xpath from stored webelement variable?


I am trying to write an XPath for this 'X' cross mark as shown in the screenshot and you can also view it via this link below. I have tried various routes but unable to get a unique XPath.

Please if anybody can help, I need it for my automated test using python selenium.

https://observatory.mozilla.org/analyze/www.cricinfo.com?third-party=false

Image 1

Image 2


Solution

  • You can get unique XPath for each Cross-button using the test name of relative row, e.g.:

    //td[span/a='Content Security Policy']/following-sibling::td[@id='tests-content-security-policy-pass']
    

    In Python you can siplify it as:

    xpath_template = "//td[span/a='{}']/following-sibling::td[@id='tests-content-security-policy-pass']"
    content_security_xpath = xpath_template.format('Content Security Policy')
    cookies_xpath = xpath_template.format('Cookies')