【问题标题】:Finding element anchor class element with selenium python causing css selector error使用 selenium python 查找元素锚类元素导致 css 选择器错误
【发布时间】:2021-06-24 16:21:47
【问题描述】:

使用 HTML:

<a class="paginate_button next" aria-controls="tabcc" data-dt-idx="7" tabindex="0" id="tabcc_next">Next</a>

我试图按类来选择“下一个”innerHTML。我正在尝试:

next_page = self.driver.find_element_by_class_name('paginate_button next')

next_page = WebDriverWait(self.driver, 20).until(
   EC.presence_of_element_located((By.CLASS_NAME, "paginate_button next"))
)

但两者都报错:

 raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".paginate_button next"}
  (Session info: chrome=91.0.4472.114)

用 ID 做同样的想法似乎是有效的:

next_page = self.driver.find_element_by_id('tabcc_next')

但是,对于我正在做的事情,我需要它为类名工作。

任何帮助将不胜感激!

【问题讨论】:

    标签: python selenium xpath css-selectors


    【解决方案1】:

    您正在尝试根据其 PARTIAL 类属性定位元素,而使用 find_element_by_class_name 定位元素需要 EXACT 类属性值。
    可以使用 css_selectors 或 XPath 按部分属性值选择元素。
    所以你可以使用 css_selector 代替。

    next_page = self.driver.find_element_by_css_selector('.paginate_button.next')
    

    next_page = WebDriverWait(self.driver, 20).until(
       EC.presence_of_element_located((By.CSS_SELECTOR, ".paginate_button.next"))
    )
    

    或 XPath

    next_page = self.driver.find_element_by_xpath("//a[contains(@class,'paginate_button next')]")
    

    next_page = WebDriverWait(self.driver, 20).until(
       EC.presence_of_element_located((By.XPATH, "//a[contains(@class,'paginate_button next')]"))
    )
    

    【讨论】:

      【解决方案2】:

      CLASS_NAME 不支持空格,您可以在类名paginate_button next 中看到空格。

      如果您想继续相同的操作,您需要使用CSS_SELECTOR,下面的小改动应该适合您:

      next_page = WebDriverWait(self.driver, 20).until(
         EC.presence_of_element_located((By.CSS_SELECTOR, "a.paginate_button.next"))
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-16
        • 2021-11-21
        • 2018-10-22
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 2021-11-17
        相关资源
        最近更新 更多