find_element_by_class_name class spaces does not work

I'm trying to use find_element_by_class_name where the class has spaces and it does not work:

Here is the code:

<a class="yt-simple-endpoint style-scope yt-formatted-string" href="/user/santanderbrasil">Santander Brasil</a>

I want the get the content "Santander Brasil"

I tried the following:

driver.find_element_by_class_name("yt-simple-endpoint.style-scope.yt-formatted-string")    
driver.find_element_by_class_name("a.yt-simple-endpoint.style-scope.yt-formatted-string")

and

driver.find_element_by_class_name("a.yt-simple-endpoint.")

none of the worked...

Any help?

Upvotes: 4

Views: 7462

Answers (4)

mhawke
mhawke

Reputation: 87054

All of these work for me (Firefox driver):

yt-simple-endpoint
style-scope
yt-formatted-string
yt-simple-endpoint.style-scope.yt-formatted-string

Note that the last class name is actually the same as the first one in your question. It works because Selenium internally converts the class name into a CSS selector and then uses it for the search. If you want to nail things down for specific tags, e.g. only match <a> tags with those classes then you will need to look at CSS selectors and other options such as XPath.

from selenium import webdriver

driver = webdriver.Firefox()
driver.get("file:///tmp/test.html")

for class_name in 'yt-simple-endpoint', 'yt-formatted-string', 'style-scope', 'yt-simple-endpoint.style-scope.yt-formatted-string':
    e = driver.find_element_by_class_name(class_name)
    print(e.text)
driver.close()

Output

Santander Brasil
Santander Brasil
Santander Brasil
Santander Brasil

The test.html file contains:

<html>
<head><title>Test</title></head>
<body>
<a class="yt-simple-endpoint style-scope yt-formatted-string" href="/user/santanderbrasil">Santander Brasil</a>
</body>
</html>

Upvotes: 0

Guy
Guy

Reputation: 50809

Those are three separated classes, find_element_by_class_name() receives only one class as parameter. For example

driver.find_element_by_class_name('yt-simple-endpoint')

The . you added between the classes represent class in css_selector. You can use it to locate the element by all three classes use css_selector

driver.find_element_by_css_selector('.yt-simple-endpoint.style-scope.yt-formatted-string')

Or by xpath

driver.find_element_by_xpath('//a[@class="yt-simple-endpoint style-scope yt-formatted-string"]')

Upvotes: 3

Pierre Baran
Pierre Baran

Reputation: 160

Try this

driver.find_element_by_xpath("//div[contains(@class, 'yt-simple-endpoint') and contains(@class, 'style-scope') and contains(@class, 'yt-formatted-string')]"")

Not sure about the find_element_by_xpath method because i don't use selenium in python, but whatever that function is, selector should do the trick.

Hope this helps.

Upvotes: 0

Grasshopper
Grasshopper

Reputation: 9058

Use the css selector function instead.

driver.find_element_by_css_selector("a.yt-simple-endpoint.style-scope.yt-formatted-string")

Upvotes: 4

Related Questions