简体   繁体   English

选择 <li> FirefoxDriver中的元素

[英]Select <li> element in FirefoxDriver

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 . 在上方,我要单击“ Services I'm using FirefoxDriver . 我正在使用FirefoxDriver

So how can i achieve it ? 那么我该如何实现呢? help me out. 帮帮我。

The reason why you're probably stuck at this is because you don't know XPath expressions . 之所以会陷入困境,是因为您不知道XPath表达式

There are numerous strategies how to locate elements in WebDriver : 很多策略可以在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. 谨慎使用这些链接,因为有时似乎实际上不是真正的<a>元素的链接。

  • 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. 学习并喜欢CSS选择器,因为它们通常更短,更易读。 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. 这就是XPath表达式发挥作用的地方,如果明智地使用它们,它们可以匹配(几乎)所有内容。 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: 现在,这是您找到Services元素的方式:

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

The XPath expression itself: XPath表达式本身:

//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']

Here By.cssSelector will be the perfect one 在这里By.cssSelector将是完美的选择

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

Please Let me know Is the above method is working or not. 请让我知道以上方法是否有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM