Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can´t get element by class name if class name is a number

I tried to find an element by class name with the following code:

result.find_element_by_class_name("0")

result is an WebElement that contains the element I´m looking for. (I am sure about it)

The html-code is:

<tr class="0"></tr>

But if I do this I get the following Error:

selenium.common.exceptions.InvalidSelectorException: Message: The given selector 0 is either invalid or does not result in a WebElement. The following error occurred:

InvalidSelectorError: An invalid or illegal class name was specified

There are other WebElements inside result which I can find via the class name (e.g. there is an element named last and if I try to get it, it works)

So, how can I find an element by class name, if the class name is a Number? (which is a string)

like image 936
Jman Avatar asked Dec 24 '22 15:12

Jman


1 Answers

find_element_by_class_name() uses CSS selectors under the hood (source):

if by == By.ID:
    by = By.CSS_SELECTOR
    value = '[id="%s"]' % value
elif by == By.TAG_NAME:
    by = By.CSS_SELECTOR
elif by == By.CLASS_NAME:  # < HERE
    by = By.CSS_SELECTOR
    value = ".%s" % value
elif by == By.NAME:
    by = By.CSS_SELECTOR
    value = '[name="%s"]' % value

And, the problem is, according to the CSS grammar "0" is not a valid class name, since a name must start with underscore (_), hyphen (-) or a letter (relevant topic). You can locate the element by XPath in this case:

result.find_element_by_xpath("//tr[@class='0']") 
like image 159
alecxe Avatar answered Dec 29 '22 10:12

alecxe