Estoy tratando de crear un bot para acceder a Instagram, pero no entiendo por qué está dando un error, aquí está el código:

from time import sleep
from selenium import webdriver

browser = webdriver.Firefox()
browser.implicitly_wait(5)

browser.get('https://www.instagram.com/')

login_link = browser.find_element_by_xpath("//a[text()='Log in']")
login_link.click()

sleep(2)

username_input = browser.find_element_by_css_selector("input[name='username']")
password_input = browser.find_element_by_css_selector("input[name='password']")

username_input.send_keys("username")
password_input.send_keys("12345678")

login_button = browser.find_element_by_xpath("//button[@type='submit']")
login_button.click()

sleep(5)

browser.close()  

Y el error en cmd es este:

Traceback (most recent call last):
  File "C:\Users\*******\Desktop\bot instagram da net.py", line 9, in <module>
    login_link = browser.find_element_by_xpath("//a[text()='Log in']")
  File "C:\Users\*******\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
    return self.find_element(by=By.XPATH, value=xpath)
  File "C:\Users\*******\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 976, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Users\*******\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\*******\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: //a[text()='Log in']

Traté de dormir un poco después del navegador. Conseguir, pero tenía el mismo error

2
João Felipe Holanda 20 abr. 2020 a las 02:02

2 respuestas

Lo siguiente funciona para mí:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Firefox()
wait = WebDriverWait(driver, 10)
driver.maximize_window()

driver.get('https://www.instagram.com/')

wait.until(ec.element_to_be_clickable((By.NAME, "username"))).send_keys("username")
el = wait.until(ec.element_to_be_clickable((By.NAME, "password")))
el.send_keys("password")
el.send_keys(Keys.ENTER)
1
Pedro Lobito 19 abr. 2020 a las 23:13

Intenta dormir inmediatamente después del navegador. Creo que la página no ha terminado de cargarse cuando intentas acceder al elemento.

0
AviatingFotographer 19 abr. 2020 a las 23:05