Josie
Josie

Reputation: 89

Unable to locate element in selenium chromedriver even though it exists

I am trying to click the I Agree button on thetimes.co.uk website however an exception is raised stating that element could not be found.

Here is what I've tried:

import time
from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://www.thetimes.co.uk/")

time.sleep(1)

# Neither one of the below worked:
driver.find_element_by_xpath("/html/body/div/div[3]/div[3]/button[2]").click()
driver.find_element_by_css_selector("body > div > div.message.type-modal > div.message-component.message-row > button:nth-child(3)").click()
driver.find_element_by_css_selector(".message-component.message-button.no-children").click()

Website Image

Is there any cookie that I can send to the website to disable the popup or anyway to click on the I Agree button successfully?

Upvotes: 0

Views: 97

Answers (1)

gordon so
gordon so

Reputation: 309

You have ran into a classic iframe problem, the "I agree" button is within an inner HTML document, and you need to first switch into it before you can locate that button; see code example below,

import time

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver

driver = webdriver.Chrome("./chromedriver")
driver.get("https://www.thetimes.co.uk/")

iframe = (By.CSS_SELECTOR, "#sp_message_iframe_216133")
btn_agree = (By.CSS_SELECTOR, "body > div > div.message.type-modal > div.message-component.message-row > button:nth-child(3)")

iframe_element = WebDriverWait(driver, 10).until(EC.visibility_of_element_located(iframe))
driver.switch_to.frame(iframe_element)
WebDriverWait(driver, 10).until(EC.element_to_be_clickable(btn_agree)).click()

# remember to switch back out
driver.switch_to.default_content()

Upvotes: 4

Related Questions