Domanda

I want to click on a list item from a page.

<ul class="categories" id="cat1">
    <li onClick="chooseCateg(this.form, '315', 1);">Business Opp.</li>
    <li onClick="chooseCateg(this.form, '269', 1);">Cars / Trucks</li>
    <li onClick="chooseCateg(this.form, '301', 1);">Community</li>
    <li onClick="chooseCateg(this.form, '6', 1);">For Sale</li>
    <li onClick="chooseCateg(this.form, '4', 1);">Jobs</li>
    <li onClick="chooseCateg(this.form, '3', 1);">Pets</li>
    <li onClick="chooseCateg(this.form, '2', 1);">Real Estate</li>
    <li onClick="chooseCateg(this.form, '7', 1);">Services</li>
</ul>

From above I want to click on Services. I'm using FirefoxDriver.

So how can i achieve it ? help me out.

È stato utile?

Soluzione

The reason why you're probably stuck at this is because you don't know XPath expressions.

There are numerous strategies how to locate elements in WebDriver:

Those are pretty self-explanatory and should be used whenever possible:

  • By.id
  • By.name
  • By.className
  • By.tagName

Those should be used with caution as sometimes what seems to be a link is not actually a real <a> element.

  • By.linkText
  • By.partialLinkText

These are the strongest, the most advanced strategies capable of matching most of your "I don't know how to do this" stuff.

  • By.cssSelector
  • By.xpath

Learn and prefer CSS selectors as they are usually shorter and more readable. They are also faster to match. But they have their shortcomings - most notably their incapability to match text.

And that's where XPath expressions come into play, they can match (almost) everything when used wisely. They are the slowest and are hard to read, because they easily get looong. Read the interesting parts of the spec, find some tutorial online and learn them.

Now, here's how you find your Services element:

WebElement services = driver.findElement(By.xpath("//li[text()='Services']"));

The XPath expression itself:

//li[text()='Services']

just so you know and don't get scared of it when you see it, this can (and often is) be also written as:

//li[.='Services']

Altri suggerimenti

Here By.cssSelector will be the perfect one

driver.findElement(By.cssSelector("#cat1 > li:contains('Services')"))

Please Let me know Is the above method is working or not.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top