如何使用 Selenium 和 Java 单击下拉列表并增加 https://www.goindigo.in/ 上的成年乘客数量

How to click on the dropdown and increase the number of adult passengers on https://www.goindigo.in/ using Selenium and Java

我正在尝试访问 Indigo 网站 https://www.goindigo.in/

我写过代码:

System.setProperty("webdriver.chrome.driver","D:\New folder\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.goindigo.in/");       
Thread.sleep(2000);
driver.findElement(By.cssSelector("input.form- 
control.hpBookingForm.passengerInputField.pax-class-count")).click();
         
for(int i=1;i<5;i++)
{
   driver.findElement(By.xpath("/html/body/div[27]/div/div/div[2]/ul/li[1]/div/button[2]")).click();
}

我无法增加乘客数量。请检查。

将 for 循环更改为:

for(int i=0;i<5;i++)
{      
    driver.findElement(
      By.xpath("/html/body/div[27]/div/div/div[2]/ul/li[1]/div/button[2]")
    ).click();
}

引起一些等待,更改您的 xpath,并修复 for 循环。还要以跨度而不是按钮为目标,否则你会得到一个错误。

WebDriverWait wait = new WebDriverWait(driver,30);
WebElement adult =wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div/div/div[2]/ul/li[1]/div/button[2]//span")));
for(int i=1;i<5;i++)
{
  adult.click();
}

要更改其他的,请将 li[1] 更改为 li[2] 等等。 导入以下内容

import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

不要使用 Thread.sleep() 使用

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

导入

import java.util.concurrent.TimeUnit;

更好的方法是等待,而不是像我刚刚在顶部给出的示例那样隐式等待。

问题不完整,不知道错误日志是什么

因此,根据您的需要,我给出如下代码示例。

在代码中,我做了两件事来避免 + 元素 被覆盖。

  1. 关闭 cookie 同意横幅
  2. 滚动到此元素
driver.get("https://www.goindigo.in/");

/* 1. Close cookie consent banner */
driver.findElement(By.xpath("//a[@class='close-cookie']")).click();


driver.findElement(By.cssSelector("input.form-control.hpBookingForm.passengerInputField.pax-class-count")).click();

Thread.sleep(1000);
String xpath = "//div[contains(@class,'passenger-dropdown')]//li[contains(@class,'adult-pax-list')]//button[@title='Up']";
WebElement adultAdd = driver.findElement(By.xpath(xpath));

/* 2. Scroll to this element */
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("arguments[0].scrollIntoView();", adultAdd);

for (int i = 0; i < 5; i++) {
    adultAdd.click();
}

click() 在下拉列表中增加成人乘客的数量 你需要诱导 for the elementToBeClickable() and you can use either of the following :

  • xpath:

    driver.get("https://www.goindigo.in/");
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@class='form-control hpBookingForm passengerInputField pax-class-count']"))).click();
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='passenger-dropdown pax-selection-row']//ul/li[contains(@class, 'adult-pax-list')]//button[@title='Up']"))).click();
    
  • 浏览器快照: