繁体   English   中英

如何使用 Selenium 识别并单击 Accept All 按钮

[英]How to identify and click on the Accept All button using Selenium

我想找出“全部接受”按钮 xpath 以单击接受 cookies。

代码试验:

from ast import Pass
import time
from selenium import webdriver

driver = driver = webdriver.Chrome(executable_path=r'C:\Users\Nahid\Desktop\Python_code\Jobsite\chromedriver.exe')  # Optional argument, if not specified will search path.
driver.get('http://jobsite.co.uk/')
driver.maximize_window()
time.sleep(1)
#find out XPath in div tag but there has another span tag 
cookie = driver.find_element_by_xpath('//div[@class="privacy-prompt-button primary-button ccmgt_accept_button "]/span')
cookie.click()

所需元素:

<div id="ccmgt_explicit_accept" class="privacy-prompt-button primary-button ccmgt_accept_button ">
    <span>Accept All</span>
</div>

是一个具有祖先<div><span>标签。


解决方案

要单击可点击元素,您需要为element_to_be_clickable()诱导WebDriverWait ,您可以使用以下任一定位器策略

  • 使用CSS_SELECTOR

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.privacy-prompt-button.primary-button.ccmgt_accept_button>span"))).click()
  • 使用XPATH

     WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[text()='Accept All']"))).click()
  • 注意:您必须添加以下导入:

     from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC

您的 XPath 看起来是正确的,但如果可以改进的话。
此外,您应该使用WebDriverWait预期条件而不是硬编码的睡眠。
如下:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_argument("--start-maximized")

s = Service('C:\webdrivers\chromedriver.exe')

driver = webdriver.Chrome(options=options, service=s)

url = 'http://jobsite.co.uk/'

wait = WebDriverWait(driver, 10)
driver.get(url)
wait.until(EC.element_to_be_clickable((By.XPATH, "//div[@id='ccmgt_explicit_accept']"))).click()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM