java - Selenium 网络驱动程序/Java : handling calendar

标签 java selenium selenium-webdriver

我是 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:

enter image description here

您的代码现在应如下所示:

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/

相关文章:

java - 输出到屏幕时图像定位不正确

Java 如何正确转换 jdbc 查询的结果

java - JSP解析时出错

python - 打开更多 session 时 Selenium 滞后

testing - 如何使用selenium获取单选按钮的标签?

selenium-webdriver - 如何使用Selenium WebDriver检查元素是否可单击

java - 如何在 Java 中设置这些匿名类?

python - 从 python selenium 脚本打开私有(private)浏览器时如何禁用 "Insecure Connection"?

javascript - Phantom.js Webdriver.io错误: SyntaxError: DOM Exception 12

java - 无法使用 Selenium 和 Java 11 导入 o​​rg.openqa.selenium.WebDriver