如何使用Selenium Python接受cookie许可

bqucvtff  于 2023-01-24  发布在  Python
关注(0)|答案(2)|浏览(127)

我尝试用Selenium Python接受cookie同意。我尝试用CSS选择器和XPath搜索,但没有任何效果。这是HTML:

<button class="sc-1epc5np-0 dnGUzk sc-f7uhhq-2 coEmEP button button--filled button__acceptAll" type="button"><span theme="[object Object]" class="sc-1vlt5h-0 sc-1epc5np-1 cMLEOX baseText">Accept Cookies</span></button>
    <span theme="[object Object]" class="sc-1vlt5h-0 sc-1epc5np-1 cMLEOX baseText">Accept Cookies</span>
</button>

我尝试了以下代码:

WebDriverWait(driver, 40).until(EC.presence_of_element_located((By.CSS_SELECTOR, '.sc-1vlt5h-0.sc-1epc5np-1.cMLEOX.baseText')))

我也试过:

driver.find_element_by_css_selector("cMLEOX").click()
driver.find_element_by_css_selector(".cMLEOX").click()

什么都不管用。解决办法是什么?

a8jjtwal

a8jjtwal1#

所需的元素是动态元素,因此要单击()该元素而不是presence_of_element_located(),需要为element_to_be_clickable()引入WebDriverWait,并且可以使用以下locator strategies之一:

  • 使用 * CSS选择器 *:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.button__acceptAll > span.baseText"))).click()
  • 使用 * XPATH *:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(@class, 'button__acceptAll')]/span[text()='Accept Cookies']"))).click()
      • 注意**:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
6qqygrtg

6qqygrtg2#

我已经尝试了提供的解决方案与不同的页面。但这个网站的工作与同意管理平台(CMP)是不知何故隐藏。没有元素在该层可以解决 selenium -无论我等多久。
This is the Newspage I am trying to access
以下是我的尝试:

try:
    driver.get("https://www.kreiszeitung-wochenblatt.de")
    time.sleep(10)
except:
    print('Page not found')

wait = WebDriverWait(driver,15)

try:
    frame = wait.until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,'/html/body/div[2]')))
except:
    print("Frame not found")

try:
    cookie = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,'#consentDialog > div.cmp_paywall > div > div.cmp_content > div > div.cmp_middle > div > div:nth-child(1) > div:nth-child(3) > div > div')))
    cookie.click()
except:
    print('Button not found')

我总是收到“未找到框架”

相关问题