How to select element using XPATH syntax on Selenium for Python? - Stack Overflow
java - how to find xpath in selenium webdriver - Stack Overflow
Are there any gui tools for helping to find xpath and css selectors?
Using xpath to find element does not always work
How do you write an XPath in Selenium to locate an element by text?
You can use the text() function. For example:
//button[text()='Submit']
This finds a element with the visible text “Submit”. You can also use contains() for partial matches:
//button[contains(text(),'Submit')]
What’s the difference between absolute and relative XPath in Selenium?
-
Absolute XPath starts from the root (
/html) and follows the full path to the element. Example:/html/body/div[2]/ul/li[3]/a. It’s fragile—changes in the page structure can break it. -
Relative XPath starts from the middle of the document using
//and doesn’t require the full path. Example://a[@id='login']. It’s more flexible and preferred in most cases.
I want one web element of XPath through Chrome only. How can I find an XPath?
1. Right-click the web element in Chrome and select Inspect.
2. It will launch the Developer tool with highlighted Element’s HTML code.
3. Copy Xpath by right-clicking the highlighted HTML.
4. Use the copied XPath to locate this Element in Chrome later.
Videos
HTML
<div id='a'>
<div>
<a class='click'>abc</a>
</div>
</div>
You could use the XPATH as :
//div[@id='a']//a[@class='click']
output
<a class="click">abc</a>
That said your Python code should be as :
driver.find_element_by_xpath("//div[@id='a']//a[@class='click']")
In the latest version 4.x, it is now:
elem = driver.find_element(By.XPATH, "/html/body/div[1]/div/div[2]/h2/a")
To import By:
from selenium.webdriver.common.by import By
If you are using Google Chrome, right click on the button, and select Inspect in the popup. The html will open in a developer tools frame. Right click on the element in the developer tools frame, hover over copy, select copy xpath.
Here is the XPath to the form on the URL.
//*[@id="main-frame"]/div[1]/div[2]/div/div[1]/div[1]/form/regform-steps/ng-transclude/regform-step[1]/ng-form/ng-transclude/regform-button/button
WebDriver driver = new ChromeDriver();
driver.get("https://uk.match.com/unlogged/landing/2016/06/02/hpv-belowthefold-3steps-geo-psc-bowling?klid=6740");
//fill in fields
WebElement element = driver.findElement(By.xpath("//*[@id=\"main-frame\"]/div[1]/div[2]/div/div[1]/div[1]/form/regform-steps/ng-transclude/regform-step[1]/ng-form/ng-transclude/regform-button/button"));
element.click();
driver.findElement(By.xpath("//regform-button/button")).click();