thirddayouthere
thirddayouthere

Reputation: 37

Finding element anchor class element with selenium python causing css selector error

With the HTML:

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

I am trying to grab this by class to select the 'Next' innerHTML. I am trying:

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

and

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

but both give the error:

 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)

Doing the same idea with the ID seems to be working:

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

However, I need it to work for the class name for what I am doing specifically.

Any help would be appreciated!

Upvotes: 2

Views: 621

Answers (2)

Prophet
Prophet

Reputation: 33361

You are trying to locate element according its' PARTIAL class attribute while locating element with find_element_by_class_name requires the EXACT class attribute value.
Selecting element by partial attribute value possible with css_selectors or XPath.
So you can use css_selector instead.

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

or

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

or XPath

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

or

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

Upvotes: 2

cruisepandey
cruisepandey

Reputation: 29362

CLASS_NAME does not have a support for spaces as you can see in your class name paginate_button next there's a space.

In you'd like to continue the same, you'd need to use CSS_SELECTOR, below minor change should work for you :

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

Upvotes: 0

Related Questions