Why CSS selector can't have empty space but Xpath can?

Question:

I have a HTML element with a class attribute that contains empty spaces.

How come Xpath can find this element can CSS can not?

# Element: <div class="I Love StackOverFlow"></div>

self.page.locator('//div[@class="I Love StackOverFlow"]') # works
self.page.locator('div[class="I love StackOverFlow"]' # Fails

How can I make the CSS selector find the element with white / empty spaces?

Asked By: Tal Angel

||

Answers:

Class name with spaces is actually not a single class name value but several values.
In your example there are 3 values I and Love and StackOverFlow.
So, to locate that element with CSS Selector you can instead of self.page.locator('div[Class="I love StackOverFlow"]')
write it more correctly:

self.page.find_element_by_css_selector('div.I.love.StackOverFlow')
Answered By: Prophet