我是 Selenium 新手。我正在尝试处理网站日历。
当我运行下面显示的代码时,它返回“日期不匹配”(else
分支)。当我使用 contains
函数而不是 equalsignorecase
时,它选择的是 12
日期而不是 31
。
我尝试自动测试的网站是 https://www.dineout.co.in/delhi/boa-village-civil-lines-north-delhi-21335 。有人可以帮忙吗?
<小时/>public void logged_in_user_booking() throws InterruptedException
{
calender.click();
Thread.sleep(4000);
List<WebElement> dates= driver.findElements(By.cssSelector(".days"));
System.out.println(dates);
for(int i=0; i<dates.size(); i++)
{
datee = dates.get(i).getText();
if(datee.equalsIgnoreCase("31"))
{
dates.get(i).click();
break;
}
else
{
System.out.println("date did not match");
}
}
}
最佳答案
好的,所以我们同意简单/快速修复是获取 <li>
的整个列表。日期 WebElement
s(例如:天):List<WebElement> dates= driver.findElements(By.cssSelector("ul.days li"));
.
然而,这并不是解决您问题的最佳方案。学习 Selenium 是一种愉快的经历,尤其是如果方法得当的话。大多数挑战来自于理解为什么、如何和何时选择特定类型的选择器。
Problem: Select the last date from the calendar widget.
Your solution: Looping through the days
WebElements
of calendar and looking for the one which contains the last day (e.g:31
).Optimal solution: Using an xpath-selector which is better suited for this scenario as it removes the need to iterate through your entire list of monthly days.
Thus, our xpath-selector should be:
//ul[contains(@class, "days")]/li/span[text() = 31]
. See bellow a step-by-step breakdown of how I came to that result using the browser console:
您的代码现在应如下所示:
public void logged_in_user_booking() throws InterruptedException
{
calender.click();
Thread.sleep(4000);
List<WebElement> lastDay= driver.findElements(By.xpath("//ul[contains(@class, "days")]/li/span[text() = 31]"));
lastDay.click();
}
看起来好多了,对吧?! :)
后续步骤: 现在您已经知道如何使用 xpath 基于文本定位特定元素,您可以微调您的程序以检查异常:28
, 30
等
希望对您有帮助。干杯!
关于java - Selenium 网络驱动程序/Java : handling calendar,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45018181/