如何使用Selenium与Cookie模态进行交互?

时间:2019-09-12 09:49:04

标签: 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>

我的代码的最新版本是:

browser = webdriver.Chrome() 
url = "https://www.pgatour.com/competition/2019/safeway-open/leaderboard.html"
browser.get(url) 
cookieaccept = browser.find_element_by_xpath("//a[@class = 'call']")
cookieaccept.click()

错误消息是:

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

3 个答案:

答案 0 :(得分:1)

隐藏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

答案 1 :(得分:1)

存在一个标题为TrustArc Cookie Consent Manager的iframe。您需要先切换到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()

浏览器快照: enter image description here

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

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

答案 2 :(得分:0)

在您要测试的URL中,位于 iframe 中的cookie。为了在此iframe中单击某项,首先必须找到iframe。那么您必须切换到iframe。之后,您可以返回默认页面。

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

然后找到您的元素(同意并继续),然后单击它。

然后:

driver.switch_to.default_content()