[英]clicking on webelement found with selenium java
how can i get the webelement to be click based on data-key in the class _3d5d
? 如何获得基于
_3d5d
类中的数据键单击的webelement? to be more exact, if a user input the value 2002, it will have an error that tells the user "no such year, please enter again" and allow him to reenter the value. 更确切地说,如果用户输入值2002,则会出现一个错误,告诉用户“没有年份,请再次输入”,并允许他重新输入该值。 if the value keyed in matches the data-type, it will click the element.
如果键入的值与数据类型匹配,它将单击该元素。
html snippet from firebug 萤火虫的html片段
<div class="_5ay5">
<div class="_18fs">
<div id="PageScrubberPagelet_153681831442414"
data-referrer="PageScrubberPagelet_153681831442414">
<div class="_4vm5 _5ay5">
<ul id="u_0_62">
<li class="_3d5d">
<a id="u_0_5x" class="_3d5b" role="button" href="#"
data-key="recent">Recent</a>
</li>
<li class="_3d5d">
<a id="u_0_5y" class="_3d5b _-fk" role="button"
href="#" data-key="year_2015">2015</a>
</li>
<li class="_3d5d">
<a id="u_0_5z" class="_3d5b" role="button" href="#"
data-key="year_2014">2014</a>
</li>
<li class="_3d5d">
<a id="u_0_60" class="_3d5b" role="button" href="#"
data-key="year_2013">2013</a>
</li>
This is what i have attempted and it clicks on whatever year the user has input. 这是我尝试过的方法,它会在用户输入的任何年份单击。 However, this solution is sort of hard-coded where the year to be searched in coded.
但是,此解决方案是硬编码的,要在其中搜索年份。 So, is there a way that will allow the year to be retrieved if its available in the html?
因此,有没有一种方法可以让年份(如果它在html中可用)进行检索? Also, allow the user to re-input if there is no such year.
另外,如果没有这样的年份,则允许用户重新输入。
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a year (YYYY): ");
String year = reader.next(); // Scans the next token of the input as an int.
if (year.contains("recent")){
WebElement recent = dr.findElement(By.xpath("//a[contains(@data-key,'recent')]"));
recent.click();
}
else if (year.contains("2015")){
WebElement year_2015 = dr.findElement(By.xpath("//a[contains(@data-key,'2015')]"));
year_2015.click();
}
else if (year.contains("2014")){
WebElement year_2014 = dr.findElement(By.xpath("//a[contains(@data-key,'2014')]"));
year_2014.click();
}
else if (year.contains("2013")){
WebElement year_2013 = dr.findElement(By.xpath("//a[contains(@data-key,'2013')]"));
year_2013.click();
}
Try this: 尝试这个:
import org.openqa.selenium.NoSuchElementException;
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a year (YYYY): ");
String year = reader.nextInt();
try {
WebElement yearButton = dr.findElement(By.xpath("//a[contains(@data-key,'" + year + "')]"));
yearButton.click();
} catch(NoSuchElementException e) {
System.out.println("Element does not exist!");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.