Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve ID of any element using webdriver in python given value of the element

I am using selenium to record testcases in firefox. It records a button click/or any action for that matter like below,

driver = self.driver
driver.get(self.base_url + "/")
driver.find_element_by_id("ctl00__mainContent_lnkforgotpassword").click()
driver.find_element_by_id("ctl00__mainContent_ucForgotPassword1_btnNext").click()

Here the driver makes use of the find_element_by_id method to access the element and it works great.

But my requirement is to find this Id given just the text of that element, like -

If Forgot Password is a link and I want to retrieve the ID of this link, I would modify the about code as,

driver.find_element_by_id(getID("Forgot Password")).click().

So is there a way to write getId() function so as to retrieve the ID of the link Forgot Password (Or Id of some Label/Button in other cases) from the current open page?

like image 951
Vinay Avatar asked Nov 22 '16 05:11

Vinay


1 Answers

There is no way to retrieve the ID (or any attribute) directly the way you mentioned.

But, you can find any attribute/property of a web element once you find that web element only.

do as follows:

elem = driver.find_element_by_link_text("Forgot Password") / returns Web Element, store it in some variable.
print elem.get_attribute("id")
print elem.get_property("id") // or use get_property

Reference:

  1. http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.remote.webelement
like image 67
Naveen Kumar R B Avatar answered Oct 16 '22 17:10

Naveen Kumar R B