Serial Serial - 1 month ago 20
Python Question

Cannot find Twitter element by name using Selenium and Chrome Webdriver

I'm trying to remotely log into twitter and tweet using selenium and Chrome webdriver but I can't seem to get it before I do anything else I want to just test if I can write into the username and password areas but I cant even do that.

Here is my Code:

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

driver = webdriver.Chrome()

elem = driver.find_element_by_name("session[username_or_email]")

When I try this it opens the command prompt to run chromedriver.exe then it opens the chrome window but then nothing else happens and it gives me this error message:

Traceback (most recent call last):
File "C:\Python27\Project\", line 10, in <module>
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\", line 162, in send_keys
self._execute(Command.SEND_KEYS_TO_ELEMENT, {'value': typing})
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\", line 228, in _execute
return self._parent.execute(command, params)
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\", line 165, in execute
File "C:\Python27\lib\site-packages\selenium\webdriver\remote\", 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)'

Can anyone tell me what's the problem and how to fix it!


Yes, find_element_by_id, find_element_by_xpath or find_element_by_css_selector should be used in this particular case.

I suspect elem = driver.find_element_by_name("session[username_or_email]") won't work because of the square brackets.

For anyone else who needs to handle square brackets using Selenium, using css selector or xpath should be easier as shown in the following example (square brackets are in class names in this example):

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

# won't work, as the special meaning of square brackets in css selector

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