Serial Serial - 18 days ago 8
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()

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


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\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)'


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

Answer

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" />
</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