How to avoid Compound Class name error in Page Object?

与世无争的帅哥 提交于 2019-11-27 20:15:42

Use a CSS selector instead:

.country.name

The important thing to note is that this example is wrong! If "country name" is meant as a name of a country, that is. Class names can't have spaces in them. In fact, the class attribute is a space-separated list of classes. That means that if you have a class country name, it's not one class, it's two different classes your element belongs to - the first is country, the second is name!

Therefore, fix your classes, if they're wrong. If they're not, use a CSS selector, it's the only reliable way to match multiple classes (apart from a very long and complicated XPath expression). Don't use trivial XPath expressions or CSS selectors with naive attribute comparison (//*[@class='country name'] or *[class='country name']), that's just plain wrong.

You can use with this

By.cssSelector("*[class^='classname']");

^ is for if you entering beginning of the class name, 
$ is for if you entering ending of the class name usage example below with sample class name: tech random corner text_left

By.cssSelector("*[class^='tech']");
By.cssSelector("*[class$='text_left']");

You can use one of these class names, for example

:class => 'country' 

or

:class => 'name'

if it can't help you then you should switch to use other type of selector :css or :xpath

But note that in case of :css you write:

:css => '.country.name'

and in case of :xpath:

:xpath => '//div[@class='country code']

both should work

If you have class names which have spaces in them you will get this error. One way of avoiding is creating an xpath for identifying the element. If you show the html I can create the xpath. Also try using class names as multiple objects will have the same class name.

You will have to either remove the space from the class name, in which case Selenium should still in theory find the elements you need or, use a CSS selector and combine it with a period/full stop to concatenate the class names together.

i.e, using a CSS selector to target this:

<div class="country code"></div>

You could use:

div.country.code

or you could make your selector a bit more elaborate:

div[class='country code']
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!