使用selenium python查找元素锚定类元素导致css选择器错误

2024-05-20 05:27:48 发布

您现在位置:Python中文网/ 问答频道 /正文

使用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')

然而,我需要它来为我正在做的事情的类名工作

任何帮助都将不胜感激


Tags: selfidbyhtmldriverpagebuttonelement
2条回答

类名不支持空格,正如您在类名中看到的那样paginate_button next有一个空格

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

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

您试图根据元素的“分部类属性”定位元素,而使用find_element_by_class_name定位元素需要准确的类属性值。
可以使用css_选择器或XPath按部分属性值选择元素。
因此,您可以使用css_选择器

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')]"))
)

相关问题 更多 >