我想学习硒,我有一个问题是等待元素,我会解释它。硒等元素
我正在做一个Java程序,使用谷歌翻译自动翻译。 但由于谷歌翻译的异步性质,没有办法在没有等待的情况下获取元素,代码崩溃是因为它没有找到元素,并且元素在代码需要时不存在,所以您必须稍等一会,直到服务器响应您的请求。
我认为这不是一个疏远的情况处理硒和网页,所以我认为必须有一个简单的方法来做到这一点。 到目前为止,这是我创建的用于管理情况的代码。
public void translation(String s) {
System.setProperty("webdriver.chrome.driver", "C:\\Robots\\chromedriver.exe");
WebElement webDriver = new ChromeDriver();
这是代码我觉得应该有一个更好的方式做,
我使用的方法要等到翻译准备
waitForElement("//*[@id='result_box']");
System.out.println("prhase: " + s + " tranlsation: " + response.getText());
webDriver.close();
}
private void waitForElement(String element) {
WebElement response;
do {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response = webDriver.findElement(By.xpath(element));
} while (response.getText().isEmpty());
}
灿你说我怎么容易吗?
有一个多等待方法来等待一个元素引用这个链接http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp它会帮助你。 –