8

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?

2 Answers 2

13

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
Sign up to request clarification or add additional context in comments.

3 Comments

That works fine for links. What about any other element, like a button, label,etc
same way you did for link text. First, identify the element using one of its attributes (class, text, link text, name etc.) then you can retrieve ID from that Web Element if present.
find_element_*() API returns WebElement, which you can use to retrieve properties/attributes of the web element using WebElement API. Added reference URL for WebElement API in the answer.
0

There are two steps you need to do: 1. Get the element by link text 2. From that element get the attribute value of id.

You can try something similar to the below code to create your function: (Note: Below code is JAVA, you would need to write the similar python code)

WebElement ele = driver.findElement(By.linkText("Forgot Password"));
ele.getAttribute("id");

Below links will help as a reference:

How to grab just element id - using Selenium WebDriver 2

http://www.software-testing-tutorials-automation.com/2014/01/how-to-locate-element-by-link-text-or.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.