Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select element using XPATH syntax on Selenium for Python?

consider following HTML:

<div id='a'>   <div>     <a class='click'>abc</a>   </div> </div> 

I want to click abc, but the wrapper div could change, so

driver.get_element_by_xpath("//div[@id='a']/div/a[@class='click']") 

is not what I want

i tried:

 driver.get_element_by_xpath("//div[@id='a']").get_element_by_xpath(.//a[@class='click']") 

but this would not work with deeper nesting

any ideas?

like image 617
user2534633 Avatar asked Sep 26 '13 17:09

user2534633


People also ask

How use Selenium for XPath in python?

Go to the First name tab and right click >> Inspect. On inspecting the web element, it will show an input tag and attributes like class and id. Use the id and these attributes to construct XPath which, in turn, will locate the first name field.

Can we use XPath in python?

XPath Standard Functions. XPath includes over 200 built-in functions. There are functions for string values, numeric values, booleans, date and time comparison, node manipulation, sequence manipulation, and much more. These expressions can be used in JavaScript, Java, XML Schema, Python, and lots of other languages.

How do you click XPath in python?

We can click a button with Selenium webdriver in Python using the click method. First, we have to identify the button to be clicked with the help of any locators like id, name, class, xpath, tagname or css. Then we have to apply the click method on it. A button in html code is represented by button tagname.


1 Answers

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']") 
like image 188
Arup Rakshit Avatar answered Oct 05 '22 14:10

Arup Rakshit