python - Selenium Python,我尝试关闭一个 cookie 按钮,但它结束了点击广告
问题描述
我试图关闭 whoscored.com 上的 cookie 按钮,我找到了该按钮,但是当程序点击时,它似乎点击了按钮后面的广告,它最终打开了一个新页面而不是关闭 cookie 按钮。知道我能做什么吗?
url='https://www.whoscored.com/Search/?t=Crystal+Palace'
browse=webdriver.Chrome()
browse.get(url)
time.sleep(4)
cacheButton=browse.find_elements_by_xpath('//button')
cacheButton[1].click() #This is the "I ACCEPT" button.
这是按钮的html:
<button class="qc-cmp-button" onclick="window.__cmpui("setAndSaveAllConsent",!0)"> I accept </button>
如果有人可以帮助我,将不胜感激。
解决方案
诱导WebDriverWait
() 并等待element_to_be_clickable
() 和后续xpath
。
WebDriverWait(browse,15).until(EC.element_to_be_clickable((By.XPATH,"//button[@class='qc-cmp-button' and contains(.,'I accept')]"))).click()
添加以下库。
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
代码:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
url='https://www.whoscored.com/Search/?t=Crystal+Palace'
browse=webdriver.Chrome()
browse.get(url)
WebDriverWait(browse,15).until(EC.element_to_be_clickable((By.XPATH,"//button[@class='qc-cmp-button' and contains(.,'I accept')]"))).click()
浏览器截图:
更新:
cookie=btn=WebDriverWait(browse,15).until(EC.presence_of_element_located((By.XPATH,"//button[@class='qc-cmp-button' and contains(.,'I accept')]")))
browse.execute_script("arguments[0].click();", cookie)
推荐阅读
- html - 如何使用 SQL 查询而不是函数从字段中删除 HTML
- android - Android 版本 APK(已签名)中的哨兵上传失败消息?
- javascript - 如何改进我的脚本以在 Google Apps 脚本中拖动多个单元格?
- javascript - 如何在屏幕上显示测验结果?
- amazon-web-services - 创建堆栈时的 AWS CloudFormation 模板验证
- c++ - 从 CMake 生成 Eclipse CDT 项目的问题
- java - 如何使用 MapStruct 将枚举映射到它自己的属性?
- c - 在c中没有递归的表达式树评估
- php - 对私有示例通道进行身份验证时出错(带 Redis 的 LUMEN 5.8)
- amazon-web-services - 将子网修改为 VPC 终端节点