Search code examples
pythonseleniumselenium-webdriverxpath

find_element_by_xpath() shows syntax error using Selenium with Python


I tried to connect to Twitter using selnium in python. I could not connect using Name or Xpath. The xpath is copied by clicking Inspect and then copy xpath of the specific element. All the tutorials I found regarding connecting to Twitter are old and irrelevant. I enclose the code here. I have error on @id="layers"

Image of the code:

image of the code

I would be very happy to help.

Code:

from threading import Thread
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from selenium.webdriver.support import wait

driver=webdriver.Chrome(executable_path="C:\\Webdrivers\\chromedriver.exe")
driver.get("https://twitter.com/i/flow/login")
search=driver.find_element_by_xpath("//*[@id="layers"]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div[1]/div/div[5]/label/div/div[2]/div/input")
search.send_keys("orlaharty1@gmail.com")
button=driver.find_element_by_xpath("//*[@id="layers"]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div[1]/div/div[6]/div")
button.click()

Solution

  • You are using double quotes twice. Instead paste the xpath to single quotes 'xpathblabla' Also, add driver.implicity_wait(seconds) so you won't get any errors if your driver is fetching elements that aren't loaded yet

    driver.get("https://twitter.com/i/flow/login")
    
    #add this line
    driver.implicitly_wait(10)
    #                                  single quotes
    search=driver.find_element_by_xpath('//*[@id="layers"]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div[1]/div/div[5]/label/div/div[2]/div/input')
    search.send_keys("orlaharty1@gmail.com")
    button=driver.find_element_by_xpath('//*[@id="layers"]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div[1]/div/div[6]/div')
    button.click()