在jobsite.co.uk网站上找不到含 selenium 的XPath

mec1mxoz  于 2022-11-10  发布在  其他
关注(0)|答案(2)|浏览(120)

我想找出单击Accept Cookie的“Accept All”按钮的XPath。
代码试验:

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

ql3eal8s1#

所需的元素:

<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,您可以使用以下locator strategies之一:

  • 使用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
jm81lzqq

jm81lzqq2#

您的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.ID, "ccmgt_explicit_accept"))).click()

相关问题