简体   繁体   中英

Selenium findElement(By by) equivalent in Python

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.

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

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")
 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):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM