通过标题属性获取页面元素 - Selenium 和 Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31269227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 18:22:09  来源:igfitidea点击:

Get page element by title attribute - Selenium and Java

javahtmlselenium

提问by Vlad Vidac

I'm trying to get the image which has the word "Collector" in its title and click on it. This is the html code for the image and its link:

我正在尝试获取标题中带有“收藏家”一词的图像,然后单击它。这是图像及其链接的 html 代码:

<a href="javascript:*command*" title="Level III: KPI Collector RYG of D D/Testing - SYS">
<img src="*unusable link because it's only valid for the specific page*" title="Level III: KPI Collector RYG of D D/Testing - SYS">

The <a>and <img>tags are nested in a table cell and some divs. I didn't write the html code so don't yell at me if it's ugly :p
Here is the java code where I try to do it:

<a><img>标签嵌套在一个表格单元格和一些div。我没有编写 html 代码,所以如果它很丑,请不要对我大喊大叫:p
这是我尝试执行的 java 代码:

WebElement trafficLight = driver.findElement(By.xpath("//img[contains(@title,'Collector')]"));
trafficLight.click();

The error I get is:

我得到的错误是:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"xpath","selector":"//img[contains(@title,'Collector')]"}

I'm pretty sure the xpath is ok so I don't think that's the issue.

我很确定 xpath 没问题,所以我不认为这是问题所在。

采纳答案by Tom Trumper

As the imgWebElement is within a frame, you will need to switch focus to that frame before you perform any action on that WebElement. You can do that using WebDriver's switchTo()method like so:

由于imgWebElement 位于框架内,因此在对该WebElement 执行任何操作之前,您需要将焦点切换到该框架。您可以使用 WebDriver 的switchTo()方法来做到这一点,如下所示:

driver.switchTo().frame(frameLocator);

The frame locator can be either its (zero-based) index, name or id attribute, or a previously located WebElement.

框架定位器可以是它的(从零开始的)索引、名称或 id 属性,也可以是以前定位的 WebElement。

Once you have switched focus to the required frame, you should then be able to interact with the WebElement using the same code in your initial post.

将焦点切换到所需的框架后,您应该能够使用初始帖子中的相同代码与 WebElement 进行交互。

回答by Hari kishen

Please try this. It will resolve your problem.

请试试这个。它将解决您的问题。

WebElement frameSwitch = driver.findElement(By.xpath("Give iframe Xpath location")); 
driver.switchTo().frame(frameSwitch); //Switch control to iframe.

//Perform your steps (I.e Click on Image)
driver.findElement(By.xpath("//img[contains(@title,'Collector')]")).click();

driver.switchTo().defaultContent(); //Come out of iframe.