lurkagurka
lurkagurka

Reputation: 25

How to deal with spaces in a HTML/JavaScript class name

I am having problems getting data from a element using Selenium with the line:

bets = driver.find_elements_by_class_name('sgl-ParticipantFixtureLink gl-Market_General-cn1 ')

I can get the data by using XPath, but getting all the values since they have the same class name would be more efficient.

Since I am pretty new to HTML, Python, JavaScript etc, I was wondering if need to change the class name, using:

"_" or "-"

to fill up the blank spaces in the class name?

bets = driver.find_elements_by_class_name('sgl-ParticipantFixtureLink-gl-Market_General-cn1-')

or

bets = driver.find_elements_by_class_name('sgl-ParticipantFixtureLink_gl-Market_General-cn1_')

It does not seem to return any value, but neither does it return null.

Upvotes: 1

Views: 639

Answers (2)

Samathingamajig
Samathingamajig

Reputation: 13245

When an element has spaces in the class attribute, that means it has multiple classes, so you'll need to handle that another way.

One option is with CSS selectors.

https://selenium-python.readthedocs.io/locating-elements.html#locating-elements

https://selenium-python.readthedocs.io/api.html#locate-elements-by

bets = driver.find_elements_by_css_selector('.sgl-ParticipantFixtureLink.gl-Market_General-cn1')

Start with a period (.) and have a period between each subsequent class (nothing at the end)

This will return a list containing all in elements with both of those classes

For example, if you wanted to convert this to a list of text, you would do this:

# after the code above
texts = [bet.text for bet in bets]

Upvotes: 1

Prophet
Prophet

Reputation: 33353

As mentioned by Samathingamajig in case of multiple class names the simplest way to locate the element(s) is to use css_selector.
If there are several elements matching that locator you can iterate through the list of elements and get text from each one of them. Like this:

bets = driver.find_elements_by_css_selector('.sgl-ParticipantFixtureLink.gl-Market_General-cn1')
for bet in bets:
    text = bet.text
    print(text)

Upvotes: 0

Related Questions