I am using Python 3.10 and I am trying to log in on Twitter using Selenium. I am not able to get a hold of the input button to enter my user. Looks like the selenium documentation has changed. I could not find a good example.
This is the code I try:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys # not sure why this is greyed out
Chrome_driver_path = "C:/Users/osman/OneDrive/Desktop/chromedriver.exe"
driver = webdriver.Chrome(Chrome_driver_path)
driver.get("https://www.twitter.com/login")
First_Name = driver.find_element(By.XPATH, '//*[@id="react-root"]/div/div/div/main/div/div/div/div[2]/div[2]/div/div[5]/label/div/div[2]/div/input')
First_Name.send_keys('[email protected]')
And this is the error I get:
executable_path has been deprecated, please pass in a Service object driver = webdriver.Chrome(Chrome_driver_path)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="react-root"]/div/div/div/main/div/div/div/div[2]/div[2]/div/div[5]/label/div/div[2]/div/input"} (Session info: chrome=106.0.5249.119) Stacktrace: Backtrace: Ordinal0 [0x00841ED3 2236115]
Process finished with exit code 1
CodePudding user response:
There are several problems here:
- As mentioned,
executable_path
has been deprecated. You should useService
object instead as following. - Very long absolute XPath locators are very breakable. You have to use relative locators.
- You also have to use
WebDriverWait
expected_conditions
to wait for elements to become clickable before iterating them. - And finally
from selenium.webdriver.common.keys import Keys
is greyed out since you never used this import in your code. So, it's OK, but this line could be removed to make your code clean.
The following code works:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
options = Options()
options.add_argument("start-maximized")
webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(service=webdriver_service, options=options)
url = 'https://www.twitter.com/login'
driver.get(url)
wait = WebDriverWait(driver, 20)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, '[autocomplete="username"]'))).send_keys("[email protected]")
This is what happens on www.twitter.com/login
after the above code run, screenshot: