【发布时间】:2016-12-18 15:23:01
【问题描述】:
为什么我在使用 Python 和 Selenium 时会收到此错误,我该如何解决?
NameError: name 'ElementNotVisibleException' is not defined
在 Python3.5 中运行本教程 http://www.marinamele.com/selenium-tutorial-web-scraping-with-selenium-and-python 中的以下脚本时会发生这种情况
import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
def init_driver():
driver = webdriver.Firefox()
driver.wait = WebDriverWait(driver, 5)
return driver
def lookup(driver, query):
driver.get("http://www.google.com")
try:
box = driver.wait.until(EC.presence_of_element_located(
(By.NAME, "q")))
button = driver.wait.until(EC.element_to_be_clickable(
(By.NAME, "btnK")))
box.send_keys(query)
try:
button.click()
except ElementNotVisibleException:
button = driver.wait.until(EC.visibility_of_element_located(
(By.NAME, "btnG")))
button.click()
except TimeoutException:
print("Box or Button not found in google.com")
if __name__ == "__main__":
driver = init_driver()
lookup(driver, "Selenium")
time.sleep(5)
driver.quit()
我在网上寻找答案,虽然我发现了类似的问题,但我没有找到帮助我解决此问题的答案。
【问题讨论】:
-
错误应该是不言自明的。您没有在任何地方定义或导入名为
ElementNotVisibleException的东西 -
未导入特定异常。在顶部添加
from selenium.common.exceptions import ElementNotVisibleException -
@Vineesh 谢谢!那行得通:)如果您将其发布为一个答案,我将接受它作为答案。
-
@BryanOakley 谢谢,我认为它没有定义,但不确定为什么,因为 ElementNotVisibleException 包含在 selenium.common.exceptions 中
-
好的,我会在回答区发帖
标签: python python-3.x selenium