简体   繁体   English

使用htmldriver在Selenium Java中单击没有ID,标签等的链接

[英]Clicking link with no ID,Tag etc in Selenium Java using htmldriver

How can i click the below? 我该如何点击以下内容? i Have tried using the XPath but no cigar! 我曾尝试使用XPath,但没有雪茄!

My attempt: 我的尝试:

WebElement submit = driver.findElement(By.xpath("/html/body/form/table[7]/tbody/tr[2]/td[1]/a"));
submit.click();

This is the HTML: 这是HTML:

<a href="#" onclick="return mysubit('save', window.document.jobform);">
    <img src="/shared/images/template_APC/order/submit.gif" width="90" height="17" border="0" alt="Submit Booking">
</a>

You haven't said what the error being shown is but it could be that td[1] contains multiple a elements, or that something in the xpath you defined has changed. 你还没说什么被显示的错误,但它可能是td[1]包含多个a元素,或者什么东西在你的XPath定义已经改变。 If you specifically want td1 , specify in the xpath what you want from it (ie, it could be //td[@name='cell1'] ) etc. Hard coding specific indexes in xpath, I've found, is often prone to error. 如果您特别想要td1 ,请在xpath中指定您要从中获得什么(即,它可以//td[@name='cell1'] )等。我发现,在xpath中硬编码特定索引通常很容易错误。

For the xpath I'd go with: //table[@id/class/name='xxx']//td[@id/class/name='xxx']/a[contains(@onclick,'mysubmit')] and click that. 对于xpath,我可以使用: //table[@id/class/name='xxx']//td[@id/class/name='xxx']/a[contains(@onclick,'mysubmit')] ,然后单击。 (I assume your method for submission is mysubmit and not mysubit as you've written). (我假设您的提交方法是mysubmit而不是您编写的mysubit )。

Using hard coded XPaths are prone to problems... depending on the browser they are run in, how often the structure of the HTML changes, etc. What I typically do in a situation like this is to look at the predecessors from the desired A tag. 使用硬编码的XPath容易出现问题……取决于运行它们的浏览器,HTML结构的更改频率等。在这种情况下,我通常要做的是从所需的A查看前辈A标签。 Hopefully you can find one with an ID or class , etc. that can serve as a start. 希望您可以找到一个IDclass等可以作为开始的对象。 You likely won't be this lucky but you hopefully will get the idea... 你可能不会得到这样的运气,但你希望能得到的想法......

<div id="home">
    <a href="#" onclick="return mysubit('save', window.document.jobform);">
        <img src="/shared/images/template_APC/order/submit.gif" width="90" height="17" border="0" alt="Submit Booking">
    </a>
</div>

In this case you can use a CSS Selector to quickly get the A you want. 在这种情况下,您可以使用CSS选择器快速获取所需的A

driver.findElement(By.cssSelector("#home > a")).click();

The CSS Selector, "#home > a" , means starting with the element with an ID of "home" ( #home ) find immediate children ( > ) that are a tags. CSS选择器"#home > a"表示从ID为“ home”( #home )的元素开始,查找a标签的直接子级( > )。

CSS Selectors reference CSS选择器参考

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

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