尝试使网站自动化,但单击按钮后未得到任何响应

时间:2019-04-23 05:27:00

标签: selenium

我正在尝试使用selenium来自动化网站,该值输入很好,但是当单击按钮而未在网站中显示任何响应时,程序将终止,这是什么原因?

System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("somewebsite.html");
driver.findElement(By.xpath("//*[@id='abc']")).sendKeys("0000");
driver.findElement(By.xpath("//*[@id='xyz']")).sendKeys("5020");
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.findElement(By.xpath("//span[contains(text(), 'Click 
Me')]")).click();
//after clicking this button website is not showing any responce and 
the program terminates successfully
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//* 
[@id='pqr']")

1 个答案:

答案 0 :(得分:0)

最好使用显式等待而不是隐式等待。显式等待将等待您给定的条件,当条件满足时,它将停止等待。

由于您正在等待单击后出现的内容,因此请使用显式等待来等待该元素可见。

尝试一下:

// declare a wait first and you could reuse it
    WebDriverWait wait = new WebDriverWait(driver, 30);

    WebElement button = driver.findElement(By.xpath("//span[contains(text(), 'Click Me')]"));

// instead of implicit wait this waits for the button to be clicable and doesn't wait more than necessary
    wait.until(ExpectedConditions.elementToBeClickable(button));
    button.click();

    WebElement expected_element = driver.findElement(By.id("pqr"));

//this waits for your expected element to be visible after click. if the element is not visible after 30 seconds it will throw timeout exception
    wait.until(ExpectedConditions.visibilityOf(expected_element));