1

Using Selenium (Python), how do we pass the By object to findElement()?

Java (this works)

By locater = By.id("username")
WebElement elem = driver.findElement(locater)
elem.SendKeys("tester")

Python (this fails)

locater = By.id("username")
elem = driver.find_element(locater)
elem.send_keys("tester")

Error i get in python is 'str' object is not callable. I looked this up in other SO conversations and its because python expects something like By.ID or By.XPATH etc.

I need a way to pass the By object and wondered it it is possible. Thanks in advance.

3 Answers 3

3

In Python By.XPATH is not a method of class By(), but string variable:

By.XPATH == "xpath"

Try to implement below code:

from selenium.webdriver.common.by import By

locator = (By.XPATH, oSignUp.listformfieldxpaths[0])
elem = oDriver.getdriver().find_element(*locator)
elem.send_keys("tester")

Note that find_element() should receive 2 arguments: by and value. Both are strings

Sign up to request clarification or add additional context in comments.

3 Comments

Many Thanks @Andersson. Accepting this answer as closest to what i wanted. Would you mind describing why the * is prefixed to locater?
as type of locator is tuple you need to use *locator syntax to unpack values from tuple. To be clear: find.element(locator) == find.element((By.XPATH, oSignUp.listformfieldxpaths[0])), find.element(*locator) == find.element(By.XPATH, oSignUp.listformfieldxpaths[0])
Thanks again @Andersson for the details & quick response. This has been very helpful indeed.
1

I believe this should work. Give it a shot

xpath = oSignUp.listformfieldxpaths[0]
elem = oDriver.getdriver().find_element(By.XPATH, xpath)
elem.send_keys("tester")

Comments

0
 web_element=driver.find_element(By.ID,'id_value')

or

web_element=driver.find_element('id','id_value')

find_element has two parameter first one is locator strategy and second one is locator value.

method signature

     def find_element(self, by=By.ID, value=None):

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.