Skip to content
Advertisement

find_element(By.CLASS_NAME…) InvalidSelectorException

I need to navigate to the object with special class, that changes every page refresh

So i decided to use bs to find the element class, that works, but selenium raises an exception about invalid selector. class is existing, i can find it in page source. There are some spaces at the beginning and at the ending of class name that bs not showing fo some reason, but even if I add them to the class name manually, problem is still there. `

#opening vehicle menu
vehicle_menu_parent = soup.find('div', string='ЛЕГКОВЫЕ АВТОМОБИЛИ').parent
vehicle_menu_class = '" ' + str(vehicle_menu_parent)[11:50] + '   "'
print(vehicle_menu_class) # " x-grid-cell x-grid-cell-gridcolumn-1331   "
with open('test.html', 'w', encoding='utf8') as file:
    file.write(driver.page_source)
vehicle_menu = driver.find_element(By.CLASS_NAME, vehicle_menu_class)
action.move_to_element(vehicle_menu).double_click().perform()
time.sleep(10)

` page source

Advertisement

Answer

driver.find_element expects two arguments: By and a string containing a class name.
vehicle_menu_class variable is built using this line: vehicle_menu_class = '" ' + str(vehicle_menu_parent)[11:50] + ' "'. So, in this case it is " x-grid-cell x-grid-cell-gridcolumn-1331 ".
The spaces inside the class attribute are class names separators. This element has 2 classes: x-grid-cell and x-grid-cell-gridcolumn-1331. So you need to skip all the spaces.
In the end your locator should be constructed like that:

driver.find_element(By.CLASS_NAME, "x-grid-cell-gridcolumn-1331")

But what appears to be constructed now is:

driver.find_element(By.CLASS_NAME, "" x-grid-cell x-grid-cell-gridcolumn-1331   "")

It’s hard for python and selenium to understand these quotes and spaces.
I think building the class name like that should work:

vehicle_menu_class = str(vehicle_menu_parent)[24:50]
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement