简体   繁体   English

如何使用Java在Selenium中单击此按钮

[英]How to click this button in selenium using java

Here is the button I am attempting to click on 这是我尝试单击的按钮

<a href="/logout/?t=1550846736%2C09865a11c32ef819fb524c408c8f36cc" class="menu-linkRow">Log out</a>

Here is what I have tried 这是我尝试过的

driver.findElement(By.xpath("//a[contains(@class,'menu-linkRow')]")).click();
driver.findElement(By.xpath("//a[@href='/logout/?t=1550846736%2C09865a11c32ef819fb524c408c8f36cc']")).click();

You can try, 你可以试试,

driver.findElement(by.linkText("Log out")).click();

It would be clear if give more details, like the exception you are getting and more! 如果提供更多详细信息(如您所获得的异常信息以及更多信息),将非常清楚!

Cheers! 干杯!

Usually locating elements by xpath is a bad idea. 通常,通过xpath定位元素是一个坏主意。

Try other approaches such as: 尝试其他方法,例如:

  • Locating by CSS Selector (should be your FIRST approach everytime) (This little guide will help you understand them). 通过CSS选择器定位(每次都应该是您的第一种方法)(此小指南将帮助您理解它们)。 This includes the ability to specify patterns on element attributes such as: 这包括在元素属性上指定模式的能力,例如:
[attribute~=value]  [title~=flower] Selects all elements with a title attribute containing the word "flower"
  • Locating by any other strategy EXCEPT xpath 通过xpath以外的任何其他策略定位
  • Locating by xpath as the very last resort. 通过xpath定位是最后的手段。

Locating by xpath is considered an expensive operation and is extremely difficult to mantain. 通过xpath定位被认为是一项昂贵的操作,并且很难维护。

You can also use whatever strategy you like but getting a collection of elements and later filtering them out by means of your favourite programming technique (ie using Java8 Streams api), o just running another element search inside your elements such as: 您还可以使用任何喜欢的策略,但是要获取元素集合,然后通过自己喜欢的编程技术(即使用Java8 Streams api)将其过滤掉,或者仅在元素内部运行另一个元素搜索,例如:

element.findBy... element.findBy ...

I strongly recommend adopting css selectors, as they are being heavily used to add style to any modern web application. 我强烈建议采用css选择器,因为它们经常被用来向任何现代Web应用程序添加样式。 So if the developer managed to resolve styling with css selectors, you will also be able to. 因此,如果开发人员设法使用CSS选择器解决样式问题,您也将能够做到。

driver.findElement(by.Css('a.menu-linkRow')).click();

Also your second sentence "//a[@href='/logout/?t=1550846736%2C09865a11c32ef819fb524c408c8f36cc']" is using a session based locator which will not work on another session. 另外,您的第二句话"//a[@href='/logout/?t=1550846736%2C09865a11c32ef819fb524c408c8f36cc']"使用的是基于会话的定位器,该定位器无法在其他会话中使用。

There is not need to use text and xpath as will be slower than css. 不需要使用text和xpath,因为它将比CSS慢。

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

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