1

我正在尝试使用 selenium 和 Chrome 网络驱动程序远程登录 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)' 

谁能告诉我是什么问题以及如何解决它!

4

2 回答 2

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')
于 2016-11-22T08:02:23.593 回答
1

Yes, find_element_by_id, find_element_by_xpathorfind_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
于 2013-05-05T23:13:54.660 回答