Home > Mobile >  It closes when click runs. (selenium)
It closes when click runs. (selenium)

Time:12-13

It closes when click runs.

and ı wanna just click button. ı wanna do click that xpath. but its doesnt work. it close without doesnt click. so it open edge. waiting waiting and close. it didint run my click command. and there a error. its "webdriver object has no attribute find_element_by_xpath"

from selenium import webdriver
import time
driver = webdriver.Edge()
driver.get("https://www.instagram.com/")

time.sleep(7)

log_in = driver.find_element_by_xpath("//*[@id='mount_0_0_ h']/div/div/div/div[1]/div/div/div/div[1]/section/main/article/div[2]/div[2]/div/p/a/span")
log_in.click()

driver.close()

CodePudding user response:

I think this is what you want:

# Needed libs
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

#Open the browser
driver = webdriver.Edge()
driver.get("https://www.instagram.com/")

# Wait and click for allow cookies button
allow_cookies_button = date = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, f"//button[text()='Only allow essential cookies']")))
allow_cookies_button.click()
# Wait and click for Sign in button
signup_button = date = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, f"//span[text()='Sign up']")))
signup_button.click()

# This time.sleep is to allow you to see what happened, you can delete it
time.sleep(5)
# Close the browser
driver.close()

Why your code did not work? Because as you console told you "find_element_by_xpath" is not a valid method/attribute for driver.

Advises for automation/Scraping:

  • Wait for the element you will use (it does not matter if you want to write, click or whatever, make sure the element is on the screen)
  • Try to use xpaths (Or any selector) that are understandable, you will reuse them in the future. What do you understand better, //span[text()='Sign up'] or //*[@id='mount_0_0_ h']/div/div/div/div[1]/div/div/div/div[1]/section/main/article/div[2]/div[2]/div/p/a/span? Good selectors will save a lot of time in the future
  • Related