Python Selenium接受cookies

tquggr8v  于 2023-01-26  发布在  Python
关注(0)|答案(2)|浏览(130)

我需要接受特定网站上的cookie,但我一直收到NoSuchElementException。这是进入网站的代码:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time

chrome_options = Options()
driver = webdriver.Chrome(executable_path='./chromedriver', options=chrome_options)

page_url = 'https://www.boerse.de/historische-kurse/Erdgaspreis/XD0002745517'
driver.get(page_url)

time.sleep(10)

我尝试使用以下命令接受Cookie按钮:

driver.find_element_by_class_name('message-component message-button no-children focusable button global-font sp_choice_type_11 last-focusable-el').click()
driver.find_element_by_xpath('//*[@id="notice"]').click()
driver.find_element_by_xpath('/html/body/div/div[2]/div[4]/div/button').click()

我在使用谷歌浏览器时从元素中复制了xpath和完整的xpath。
我是一个初学者,当谈到 selenium ,只是想使用它的一个简短的变通办法。将感谢一些帮助。

mqkwyuun

mqkwyuun1#

按钮Zustimmen位于iframe中,因此首先您必须切换到相应的iframe,然后才能与该按钮交互。

    • 代码:**
driver.maximize_window()
page_url = 'https://www.boerse.de/historische-kurse/Erdgaspreis/XD0002745517'
driver.get(page_url)
wait = WebDriverWait(driver, 30)
try:
    wait.until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//iframe[starts-with(@id,'sp_message_iframe')]")))
    wait.until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Zustimmen']"))).click()
    print('Clicked successfully')
except:
    print('Could not click')
    pass
    • 进口:**
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
2ul0zpep

2ul0zpep2#

我也遇到过类似的页面问题,我试着用selenium解决iframe和“接受全部”按钮(如@cruisebandey上面所建议的)。
但是,此页面上的弹出窗口似乎工作方式不同:
https://www.kreiszeitung-wochenblatt.de/hanstedt/c-panorama/mega-faslams-umzug-in-hanstedt_a270327
这是我尝试过的方法:

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

driver = webdriver.Chrome(executable_path="C:\\Users\\***\\chromedriver.exe")
driver.maximize_window()

try:
    driver.get("https://www.kreiszeitung-wochenblatt.de/hanstedt/c-panorama/mega-faslams-umzug-in-hanstedt_a270327")
except:
    print('Site not found')

wait = WebDriverWait(driver,10)

try:
    wait.until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,'/html/body/iframe')))
except:
    print('paywall-layover not found')

try:
    cookie = wait.until(EC.element_to_be_clickable((By.XPATH,'//*[@id="consentDialog"]/div[3]/div/div[2]/div/div[2]/div/div[1]/div[2]/div')))
    cookie.click()
except:
    print('Button to accept all not found')

相关问题