Search code examples
pythonselenium-webdriverwebdriver

driver.find_element(By.XPATH, "xpath") doesn't seem to work


Newbie here, trying to learn and searched all over.. For some reason the 'click' option for the Xpath is not doing anything. It opens the website, but from there doesn't do anything. Any idea?

Here's my code:

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options)
driver.maximize_window()
driver.get("https://google.com")
click = driver.find_element(By.XPATH, '/html/body/div[2]/div[3]/div[3]/span/div/div/div/div[3]/div[1]/button[2]/div')
click.click()

It's supposed to open Google (which it does) and then click the 'Accept' button.

Love to know what I'm doing wrong here. I've tried both the xPath & Full xPath.

Thanks in advance.


Solution

  • Refer the below refactored code with in-line explanation:

    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
    
    options = webdriver.ChromeOptions()
    options.add_experimental_option("detach", True)
    driver = webdriver.Chrome(options=options)
    driver.maximize_window()
    driver.get("https://google.com")
    # Below line will create an object of WebDriverWait
    wait = WebDriverWait(driver, 15)
    # Below line will wait for 15s until Accept All button is in the clickable state and then clicks on it
    wait.until(EC.element_to_be_clickable((By.XPATH, "//div[text()='Accept all']"))).click()
    

    Note:

    • I removed the absolute XPATH which you used with a more reliable and user readable relative XPATH - //div[text()='Accept all']
    • I have also implemented Selenium' Waits to effectively wait and perform clicks