使用Selenium和Chrome Webdriver无法按名称找到Twitter元素

时间:2013-05-05 22:04:29

标签: python selenium selenium-webdriver selenium-chromedriver

我正在尝试使用selenium和Chrome webdriver远程登录Twitter和推文,但在我做任何其他事情之前我似乎无法得到它我想测试是否可以写入用户名和密码区域但我甚至不能这样做。

这是我的代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys


driver = webdriver.Chrome()

driver.get("https://twitter.com")
elem = driver.find_element_by_name("session[username_or_email]")
elem.send_keys("test")
elem.send_keys(Keys.RETURN)

当我尝试这个时,它打开命令提示符运行chromedriver.exe然后它打开chrome窗口但是然后没有其他任何事情发生它它给了我这个错误信息:

Traceback (most recent call last):
 File "C:\Python27\Project\Auth2.py", line 10, in <module>
    elem.send_keys("test")
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line     162, in send_keys
    self._execute(Command.SEND_KEYS_TO_ELEMENT, {'value': typing})
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line   228, in _execute
    return self._parent.execute(command, params)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 165, in execute
    self.error_handler.check_response(response)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 152, in check_response
    raise exception_class(message, screen, stacktrace)
NoSuchWindowException: Message: u'no such window: target window already closed\nfrom     unknown error: web view not found\n  (Session info: chrome=26.0.1410.64)\n  (Driver info:     chromedriver=0.8,platform=Windows NT 5.1 SP3 x86)' 

任何人都可以告诉我这是什么问题以及如何解决它!

2 个答案:

答案 0 :(得分:2)

这对我有用

EmailElement = driver.find_element_by_name('session[username_or_email]')

PasswordElement = driver.find_element_by_name('session[password]')

EmailElement.send_keys('email/username_goes_here')

PasswordElement.send_keys('password_goes_here')

答案 1 :(得分:1)

是的,在这种特殊情况下应使用find_element_by_idfind_element_by_xpathfind_element_by_css_selector

我怀疑elem = driver.find_element_by_name("session[username_or_email]")因方括号而无法正常工作。

对于需要使用Selenium处理方括号的任何其他人,使用css选择器或xpath应该更容易,如下例所示(方括号在此示例中为类名):

<label class="username js-username">
    <span>Username or email</span>
    <input class="session[username_or_email]" type="text" autocomplete="on" />
</label>
# I suspect this won't work?
driver.find_element_by_class_name("session[username_or_email]")

# won't work, as the special meaning of square brackets in css selector
driver.find_element_by_css_selector(".session[username_or_email]")

# use these
driver.find_element_by_css_selector("[class='session[username_or_email]']")
driver.find_element_by_xpath("//*[@class='session[username_or_email]']") # same as usual