【问题标题】:Can't find out xpath with selenium in jobsite.co.uk website在 jobsite.co.uk 网站中找不到带有 selenium 的 xpath
【发布时间】:2022-10-25 23:08:12
【问题描述】:

我想找出单击接受 cookie 的“全部接受”按钮 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()

【问题讨论】:

    标签: python selenium xpath css-selectors webdriverwait


    【解决方案1】:

    所需元素:

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

    是一个&lt;span&gt;有祖先的标签&lt;div&gt;.


    解决方案

    要单击可点击您需要为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()
      
    • 使用路径

      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
      

    【讨论】:

      【解决方案2】:

      您的 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:webdriverschromedriver.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()
      

      【讨论】:

      • 您可以完全不使用它来进一步改进 XPath...By.ID() 在这里会更好,因为您使用的只是一个 ID。
      • 但在内部,By.ID、By.Classname 等都被转换为 CSS 选择器或 XPath。不?
      • 这真的不是重点,但是是的,它们被转换为 CSS 选择器,但为了便于阅读,By.ID 在这种情况下更有意义。一般来说,您应该首先使用 By.ID,然后尽可能选择 CSS 选择器而不是 XPath,因为它们更快、更好的支持并且语法更简单。 XPath 有一些用途,因为只有它可以通过包含的文本查找元素并进行复杂的 DOM 遍历。
      猜你喜欢
      • 1970-01-01
      • 2019-07-12
      • 2020-03-24
      • 1970-01-01
      • 2022-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多