问题描述
我只是通过pip install selenium
安装了Selenium 2,并复制了一些示例测试以确保它可以正常工作:
I just installed Selenium 2 by doing pip install selenium
and just copied some example tests to make sure that it's working:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://www.python.org")
assert "Python" in driver.title
elem = driver.find_element_by_name("q")
elem.send_keys("selenium")
elem.send_keys(Keys.RETURN)
assert "Google" in driver.title
driver.close()
我将其另存为test.py
在Mac上Home文件夹的子文件夹中,但是每当我运行python test.py
时,都会得到以下输出:
I saved that as test.py
in a sub-folder in my Home folder on my Mac, but when ever I run python test.py
, I get the following output:
Traceback (most recent call last):
File "demo.py", line 1, in <module>
from selenium import webdriver
ImportError: cannot import name webdriver
如果我将该文件移到主目录中,它将起作用.如果您不知道,我只是开始使用Selenium和编程.任何帮助,将不胜感激.
If I move that file into my Home directory, it works. If you couldn't tell, I'm just getting started with Selenium and programming. Any help with this would be much appreciated.
推荐答案
听起来您的路径中还有其他名为"selenium"的模块,而python试图导入该模块,因为它早于您的python路径.例如,您是否将文件命名为"selenium.py"?
It sounds like you have some other module in your path named "selenium", and python is trying to import that one because it comes earlier in your python path. Did you name your file "selenium.py", for example?
要调试,请使用简单的import selenium
导入硒,然后打印使用print selenium.__file__
To debug, import selenium with a simple import selenium
then print the name of the file that was imported with print selenium.__file__
如果您有一个名为"selenium.py"的文件,它不是正确的硒库,则除了重命名或删除它外,请确保您还删除了"selenium.pyc",否则python将继续尝试从中导入.pyc文件.
If you have a file named "selenium.py" which is not the proper selenium library, in addition to renaming or removing it, make sure you also delete "selenium.pyc", or python will continue to try to import from the .pyc file.
这篇关于尝试将Selenium 2与Python绑定一起使用,但是出现导入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!