How to retrieve xpath from stored webelement variable?

Viewed 202

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

3 Answers

It would be good to learn how to write an XPath expression, but while you are learning and a way to aid in that would be to utilize the browser capability to generate them for you.

In Developer Tools where you have selected that element, right click and go to:

copy -> Copy XPath

//*[@id="tests-content-security-policy-pass"]/span/svg/path

copy -> Copy full XPath

/html/body/div/div/div[1]/div[2]/div[3]/div[2]/table/tbody/tr[1]/td[2]/span/svg/path

To add to @Mads Hansen excellent explanation. I add some illustration for the steps

  1. Right click at the element and select inspect (Google Chrome)/ Inspect Element (Mozilla).

  2. Right click at element

<path fill-rule="evenodd" d="M7.48 8l3.75 3.75-1.48 1.48L6 9.48l-3.75 3.75-1.48-1.48L4.52 8 .77 4.25l1.48-1.48L6 6.52l3.75-3.75 1.48 1.48L7.48 8z"></path>

  1. Select copy

  2. Click XPath which return

//*[@id="tests-content-security-policy-pass"]/span/svg/path

The figure below should illustrate the steps better

enter image description here

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')
Related