简体   繁体   English

在硒中定位元素

[英]Locating an Element in Selenium

I am attempting to locate a link using Selenium in java. 我试图在Java中使用Selenium定位链接。 I want to use the web driver to click on the link. 我想使用Web驱动程序单击链接。 The element is a number that is a link to another page. 元素是一个数字,它是指向另一个页面的链接。 This is the section of html containing the elements I would like to locate: 这是html的一部分,其中包含我要查找的元素:

<tr class="DataGridPagerStyle">
<td colspan="5">
<span>1</span>
<a href="javascript:__doPostBack('ctl00$ctl62$dgPersonSearchResults$ctl19$ctl01','')">2</a>
<a href="javascript:__doPostBack('ctl00$ctl62$dgPersonSearchResults$ctl19$ctl02','')">3</a>
<a href="javascript:__doPostBack('ctl00$ctl62$dgPersonSearchResults$ctl19$ctl03','')">4</a>
</td>
</tr>

I would like to flip through the pages, therefore I need to locate the "a href" elements. 我想翻阅页面,因此需要找到“ a href”元素。 There are sometimes a different number of pages. 有时会有不同数量的页面。 I attempted to locate and click on these elements using the following java code: 我尝试使用以下Java代码查找并单击这些元素:

String href = doc.select("tr.DataGridPagerStyle").first().select("a:contains(" + i + ")").first().attr("href");
element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("a[href=" + href + "]")));
element.click();

The href string does contain the right value of the href attribute for a given value of i, however I get this error when running the code: href字符串确实包含给定值i的href属性的正确值,但是在运行代码时出现此错误:

The given selector a[href=javascript:__doPostBack('ctl00$ctl62$dgPersonSearchResults$ctl19$ctl01','')]
is either invalid or does not result in a WebElement. The following error occurred:
InvalidSelectorError: An invalid or illegal selector was specified

Why is this happening and what is the best way to select these elements? 为什么会发生这种情况?选择这些元素的最佳方法是什么?

You can find the links by linkText() : 您可以通过linkText()找到链接:

link = doc.select("tr.DataGridPagerStyle").first().findElement(By.linkText(i))
link.click()

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

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