当使用Selenium异常结果没有属性'urlopen'时

时间:2017-03-06 06:14:45

标签: python python-2.7 selenium webdriver urllib

现在我有来自Selenium库的测试代码。我试图测试它是否会起作用,然后对它进行自己的编辑。但是,它在“导入”部分出错了。我已经安装了所有库。请帮忙。

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0

# Create a new instance of the Firefox driver
driver = webdriver.Chrome()

# go to the google home page
driver.get("http://www.google.com")

# the page is ajaxy so the title is originally this:
print driver.title

# find the element that's name attribute is q (the google search box)
inputElement = driver.find_element_by_name("q")

# type in the search
inputElement.send_keys("cheese!")

# submit the form (although google automatically searches now without submitting)
inputElement.submit()

try:
    # we have to wait for the page to refresh, the last thing that seems to be updated is the title
    WebDriverWait(driver, 10).until(EC.title_contains("cheese!"))

    # You should see "cheese! - Google Search"
    print driver.title

finally:
    driver.quit()

例外情况如下:

Traceback (most recent call last):
  File "/Users/Edison/Desktop/supreme/supTest.py", line 12, in <module>
    from selenium import webdriver`enter code here`
  File "/Users/Edison/anaconda2/lib/python2.7/site-packages/selenium/webdriver/__init__.py", line 18, in <module>
    from .firefox.webdriver import WebDriver as Firefox  # noqa
  File "/Users/Edison/anaconda2/lib/python2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 32, in <module>
    from .extension_connection import ExtensionConnection
  File "/Users/Edison/anaconda2/lib/python2.7/site-packages/selenium/webdriver/firefox/extension_connection.py", line 24, in <module>
    from selenium.webdriver.remote.remote_connection import RemoteConnection
  File "/Users/Edison/anaconda2/lib/python2.7/site-packages/selenium/webdriver/remote/remote_connection.py", line 29, in <module>
    import urllib2 as url_request
  File "/Users/Edison/Desktop/supreme/urllib2.py", line 2, in <module>
    response = urllib2.urlopen('http://www.baidu.com/')
AttributeError: 'module' object has no attribute 'urlopen'
[Finished in 0.1s with exit code 1]

1 个答案:

答案 0 :(得分:1)

您在工作目录中有一个名为urllib2.py的脚本。当Selenium查找urllib2时,它会发现您的脚本,它没有urlopen属性。使用唯一标识符重命名该脚本,例如my_url_project.py