1

So i have a log-in script and i just try find element by class on newest version of selenium (4.8.0)

code:

button = browser.find_element(By.CLASS_NAME, 'just class name')

AND this code not working.

my stuff:

  • firefox driver - 0.32.1 (2023-02-02, b7f075124503)
  • selenium 4.8.0

this is how the documentation searches for elements - By.CLASS_NAME, By.ID, etc...

https://www.selenium.dev/documentation/webdriver/elements/finders/

tried other variations of the code like find_element_by_ID and etc, installed an additional library for the selenium (I do not remember the name).

kaliiiiiiiii
  • 925
  • 1
  • 2
  • 21
deatsin
  • 13
  • 4

2 Answers2

1

CSS classes and IDs never contain spaces. You can check if this class exists in the DOM by typing in browser console:

document.querySelectorAll('.class_name')

change class_name with class name you looking for. If the element has multiple classes each is prefixed by a period (.).

document.querySelectorAll('.class_name1.class_name2')
JeffC
  • 22,180
  • 5
  • 32
  • 55
adamczarnecki
  • 16
  • 2
  • 6
  • 1
    The shortcut to `document.querySelectorAll()` in the browser console is `$$()`, e.g. `$$('.class_name')`. It will save you some typing. `$x()` will do the same thing but for XPath. – JeffC Feb 05 '23 at 17:07
  • Also, `.querySelectorAll()` takes CSS selectors so a space means descendant, not class. Each class must be prefixed with a period (.). – JeffC Feb 05 '23 at 17:20
1

By.CLASS_NAME accepts only single classname as an argument. So you can't pass multiple classnames.


Solution

You can use either of the following locator strategies:

  • Using the classname just:

    button = browser.find_element(By.CLASS_NAME, 'just')
    
  • Using the classname class:

    button = browser.find_element(By.CLASS_NAME, 'class')
    
  • Using the classname name:

    button = browser.find_element(By.CLASS_NAME, 'name')
    

As an alternative, you can also use a css_selector as follows:

button = browser.find_element(By.CSS_SELECTOR, ".just.class.name")
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352