我正在使用Selenium开发Python,并使用以下命令driver = webdriver.Firefox()
创建了一个Web驱动程序实例,并正确创建了Web驱动程序实例。
在此之后,我试图通过str_title = driver.find_element_by_id("banner-section-title")
获取带有id的元素。但我收到以下错误:
NoSuchElementException: Message: Unable to locate element: {"method":"id","selector":"banner-section-title"}
Stacktrace:
at FirefoxDriver.prototype.findElementInternal_ (file:///tmp/tmpR0IR8T/extensions/fxdriver@googlecode.com/components/driver-component.js:10299)
at FirefoxDriver.prototype.findElement (file:///tmp/tmpR0IR8T/extensions/fxdriver@googlecode.com/components/driver-component.js:10308)
at DelayedCommand.prototype.executeInternal_/h (file:///tmp/tmpR0IR8T/extensions/fxdriver@googlecode.com/components/command-processor.js:12282)
at DelayedCommand.prototype.executeInternal_ (file:///tmp/tmpR0IR8T/extensions/fxdriver@googlecode.com/components/command-processor.js:12287)
at DelayedCommand.prototype.execute/< (file:///tmp/tmpR0IR8T/extensions/fxdriver@googlecode.com/components/command-processor.js:12229)
答案 0 :(得分:2)
首先,你必须确定你正在寻找的'id'。 您发布的错误似乎找不到该元素。
所以你也可以尝试使用
driver.implicitly_wait(<seconds>)
或
WebDriverWait(self.driver, 10).until(lambda s: s.find_element_by_id(<element>).is_displayed())
试试这个 来自selenium.webdriver.support.ui导入WebDriverWait 来自selenium.webdriver.common.keys导入密钥
page="www.yourwebsite.com"
self.driver = webdriver.Firefox()
driver = self.driver
driver.get(page)
buffer = self.driver.find_element_by_id("foo")
然后,如果有一个按钮,你可以添加.send_keys(Keys.RETURN)(这是我登录表单的例子)
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
username="myUserName"
password="myPassword"
WebDriverWait(self.driver, 10).until(lambda s: s.find_element_by_id("username").is_displayed()
textUserName = self.driver.find_element_by_id("username")
textUserName.send_keys(userName)
WebDriverWait(self.driver, 10).until(lambda s: s.find_element_by_id("password").is_displayed()
textPassword = self.driver.find_element_by_id("password")
textPassword.clear()
textPassword.send_keys(password)
btnLogin = self.driver.find_element_by_xpath("//input[@value='Login']")
btnLogin.send_keys(Keys.RETURN)
我希望这可以帮助