Home > Net >  Selenium Python find_element Xpath cant find xpath
Selenium Python find_element Xpath cant find xpath

Time:03-23

I want to access an website with selenium and than a addblock-window appears, in which i need to click a button for it to disappear. adblock window

Eventhough I can find my XPath(//button[@title='Einverstanden'], /html/body/div/div[2]/div[3]/div[1]/button[@title = 'Einverstanden'] or //button[contains(text(),"Einverstanden")]') in the browser, Xpath in Browser

I can't find it with my Python script. And i can't seem to find the mistake.

Here is my code.

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

driver  = webdriver.Firefox()

driver.implicitly_wait(30)

driver.get("``https://www.derstandard.at/story/2000134260361/endspiel-vor-gericht-prozess-gegen-boris-becker-startet-in-london``")
driver.maximize_window()
x = driver.find_element(By.XPATH, "//button[@title = 'Einverstanden']")
print(x)

This is the error I'm getting.

enter image description here

CodePudding user response:

The button is enclosed in an iframe in which case, you first need to switch to the iframe and then access the element

This should work:

driver.get("https://www.derstandard.at/consent/tcf/")
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//div[contains(@id, 'sp_message_container')]//iframe")))
WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "button[title='Einverstanden']"))).click()

Wait Imports:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

In case you want to switch to default frame again, you may use this when required:

driver.switch_to.default_content()
  • Related