如何使用 Selenium 与 cookie 模式交互?

Jon*_*ury 4 python selenium

我希望自动执行此页面上的一些点击,我将其用作测试,因为我刚刚学习 Selenium。

https://www.pgatour.com/competition/2019/safeway-open/leaderboard.html

当我加载页面时,我无法让我的代码自动接受并关闭 cookie 覆盖层,这阻止了我进一步的操作。

我尝试了各种方法来识别该元素,但每次都收到相同的消息。

我相信这是我需要识别的元素的 HTML:

<a class="call" tabindex="0" role="button">Agree and Proceed</a>
Run Code Online (Sandbox Code Playgroud)

我的代码的最新版本是这样的:

<a class="call" tabindex="0" role="button">Agree and Proceed</a>
Run Code Online (Sandbox Code Playgroud)

错误信息是:

selenium.common.exceptions.NoSuchElementException:
  Message: no such element: Unable to locate element:
  {"method":"xpath","selector":"//a[@class = 'call']"}
Run Code Online (Sandbox Code Playgroud)

Kun*_*duK 6

有一个 iframe 其中 title TrustArc Cookie Consent Manager。您需要先切换到 iframe 才能访问该元素。

诱导WebDriverWaitframe_to_be_available_and_switch_to_it 诱导WebDriverWaitelement_to_be_clickable

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
browser = webdriver.Chrome()
url = "https://www.pgatour.com/competition/2019/safeway-open/leaderboard.html"
browser.get(url)
WebDriverWait(browser,10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,'//iframe[@title="TrustArc Cookie Consent Manager"]')))
WebDriverWait(browser,10).until(EC.element_to_be_clickable((By.XPATH,"//a[@class='call'][text()='Agree and Proceed']"))).click()
Run Code Online (Sandbox Code Playgroud)

浏览器快照: 在此输入图像描述

关闭按钮,请在后面添加此代码。

WebDriverWait(browser,5).until(EC.element_to_be_clickable((By.XPATH,"//a[@id='gwt-debug-close_id'][@class='close']"))).click()
Run Code Online (Sandbox Code Playgroud)