Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium Python - Finding Elements by Class Name With Spaces

I'm writing a Python program that uses Selenium to navigate to and enter information into search boxes on an advanced search page. This website uses Javascript, and the IDs and Names for each search box change slightly each time the website is loaded, but the Class Names remain consistent. Class names are frequently reused though, so my goal is to use find_elements_by_class_name(classname) and then index through that list.

One box, for example, has the class name x-form-text x-form-field x-form-num-field x-form-empty-field, but I can't use this because selenium considers it a compound class name and throws an error. If I use just a portion of it, such as x-form-text, it can't find the element. My hope is to either find a way to allow the spaces or, if that can't be done, find a way to search for all elements whose class name contains a section of text without spaces, such as x-form-text.

Any help or thoughts would be greatly appreciated!

Edit:

I tried this code: quantminclass = 'x-form-text.x-form-field.x-form-num-field.x-form-empty-field' quantmin = '25' browser.find_elements_by_css_selector(quantminclass)[0].send_keys(quantmin)

But got an error that the list index was out of range, implying that it can't find anything. I inspected the element and that is definitely its class name, so I'm not sure how to proceed.

like image 724
Andrew Kerrigan Avatar asked Dec 05 '17 18:12

Andrew Kerrigan


People also ask

How do you write XPath for class with spaces?

XPath("//*[contains(@class,'right-body-2')]//td[contains(concat(' ',normalize-space(@class),' '), ' ac ')]/a/@href"));

Can we find element based on class name using Selenium?

Selenium By.This method makes it possible to locate an element by referencing its class name. The class() method is found inside the By class of the Selenium WebDriver JavaScript library. The class also contains other alternative methods for locating elements. let loginBtn = await driver.

How do I search for an element in ClassName?

We can find an element using the attribute class name with Selenium webdriver using the locators - class name, css, or xpath. To identify the element with css, the expression should be tagname[class='value'] and the method to be used is By. cssSelector.


1 Answers

Those are multiple classes, not a single class with spaces, just use all the classes together.

driver.find_element_by_css_selector('.class1.class2.class3')

In CSS selector a dot . is a class, you can concatenate any number class names

like image 152
Dalvenjia Avatar answered Sep 30 '22 12:09

Dalvenjia