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

2024-06-25 23:03:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找自动点击这个页面,我正在使用它作为一个测试,因为我正在学习Selenium。在

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

我无法让我的代码在加载页面时自动接受并关闭cookies覆盖,这使我无法继续。在

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

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

<a class="call" tabindex="0" role="button">Agree and Proceed</a>

我的代码的最新版本是:

^{pr2}$

错误消息是:

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

Tags: 代码httpscom消息元素wwwselenium页面
3条回答

在要测试的URL中,位于iframe中的cookie。要在这个iframe中单击某个东西,首先必须找到iframe。然后你必须切换到iframe。之后,您可以返回到默认页面。在

frame_reference = driver.find_element_by_class_name("gwt-Frame")
driver.switch_to.frame(frame_reference)

然后找到你的元素(同意并继续),然后点击它。在

然后:

^{pr2}$

有一个标题为TrustArc Cookie Consent Manager的iframe。您需要先切换到iframe才能访问元素。在

诱导WebDriverWait和{} 诱导WebDriverWait和{}

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()

浏览器快照:enter image description here

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

^{pr2}$

隐藏cookie横幅的最简单方法是为了符合gdrp。当您接受cookie模式时,它会为您的系统在浏览器上编写一个cookie。在

enter image description here

你也可以做同样的事。打开浏览器后,编写此cookie并重新加载浏览器。那么cookie模式将不会在功能中打开。在

self.webdriver.add_cookie({'name' : 'notice_gdpr_prefs', 'value' : '0,1,2:', 'domain' : self.store['base'] + url})
        self.webdriver.add_cookie({'name' : 'notice_preferences', 'value' : '2:', 'domain' : self.store['base'] + url})

我对python cookie不太了解写。你可以按照本教程编写cookie

https://chercher.tech/python/python-selenium-cookies

Python create cookies and then load a page with the cookies

相关问题 更多 >