我正在使用 python3 和 webdriver 加載此頁面:
driver.get("https://epaper.handelsblatt.com")
出現一個 cookie 視窗,我想找到并單擊“Zustimmen”按鈕將其關閉。以前我使用 ActionChains 按下 TAB 直到按鈕被選中然后輸入(不漂亮,但完成了作業)。現在 Chrome 正在跳過按鈕(即使在手動使用 TAB 時)我提到這一點是因為它可能與我無法使用 selenium 找到按鈕有關。
ActionChains(driver).send_keys(Keys.TAB *2, Keys.RETURN).perform() #close popup by two tabs and one enter
所以嘗試使用 CSS 選擇器或 XPath 來定位按鈕。但我做不到。
按鈕的 HTML 代碼:
<div class="message-component message-row" style="padding: 15px 0px; margin: 0px; border-width: 0px; border-color: rgb(0, 0, 0); border-radius: 0px; border-style: solid; width: calc(100% - 0px); height: auto; justify-content: center; align-items: center;"><button title="EINSTELLUNGEN" class="message-component message-button no-children focusable sp_choice_type_12" style="padding: 15px; margin: 10px 5px 10px 10px; border-width: 1px; border-color: rgb(102, 102, 102); border-radius: 0px; border-style: solid; font-size: 16px; font-weight: 500; color: rgb(102, 102, 102); font-family: arial, helvetica, sans-serif; width: calc(100% - 45px); background: rgb(255, 255, 255);">EINSTELLUNGEN</button><button title="ZUSTIMMEN" class="message-component message-button no-children focusable sp_choice_type_11" style="padding: 15px; margin: 10px 10px 10px 5px; border-width: 0px; border-color: rgb(0, 0, 0); border-radius: 0px; border-style: solid; font-size: 16px; font-weight: 500; color: rgb(255, 255, 255); font-family: arial, helvetica, sans-serif; width: calc(100% - 45px); background: rgb(239, 124, 0);">ZUSTIMMEN</button></div>
我試過 CSS 選擇器:
cookie = driver.find_element_by_css_selector("#notice > div:nth-child(3) > div > div.message-component.message-row > button.message-component.message-button.no-children.focusable.sp_choice_type_11")
XPath:
cookie = driver.find_element_by_xpath("/html/body/div[2]/div[2]/div[2]/div/div[4]/div[2]/div/div[11]/div[1]")
我什至嘗試用按鈕的文本來定位它。
cookie = driver.find_element_by_xpath('//button[text()="ZUSTIMMEN"]')
我很感激任何幫助!
uj5u.com熱心網友回復:
該元素位于 iframe 內。因此,在與該元素互動之前,您需要切換到該 iframe,否則它將無法正常作業。您可以在 dom 中看到有一個標題為“Iframe 標題”的 iframe 可用。
driver.get("https://epaper.handelsblatt.com/storefront/11")
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"#sp_message_iframe_648626")))
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//button[@title='ZUSTIMMEN']"))).text)
WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//button[@title='ZUSTIMMEN']"))).click()
sleep(10)
driver.quit()
進口:
from time import sleep
from selenium.webdriver.common.by import By
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/488598.html
