简体   繁体   中英

How to click on Accept button using Selenium Python

I want to click on the cookie accept button but it doesn't work. Can someone help me?

https://www.forbes.com/consent/?toURL=https://www.forbes.com/billionaires

driver.get('https://www.forbes.com/consent/toURL=https://www.forbes.com/billionaires') 
driver.implicitly_wait(15) buttonAccept =  driver.find_element_by_class_name("call") driver.implicitly_wait(5)
buttonAccept.click()

If I try to find element by xpath, I get this error:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[8]/div[1]/div/div[2]/div[2]/a[1]"}

EDIT: I think is a problem with iframe, but I don't know how to solve it. I think i need to "driver.switch_to_frame"

This is not a valid url. But can you please try the following in your code?

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

driver = webdriver.Chrome()
driver.get('https://www.forbes.com/consent/toURL=https://www.forbes.com/billionaires')
WebDriverWait(self.driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Accept']"))).click()

The cookie consent manager pop-up has an iframe s embedded into it, so you would need to switch to it first and only afterwards to click the button.

    iframe_elem = driver.find_element_by_css_selector('iframe[title="TrustArc Cookie Consent Manager"')
    driver.switch_to.frame(iframe_elem)
    accept_btn = driver.find_element_by_css_selector('.call')
    accept_btn.click()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM