昨天我发布了这个用 Java 检索数据。我很好奇是否可以在 Web 浏览器打开时运行 Java 程序,然后让它在网站上执行操作。如果我在浏览器上打开了 facebook,它可以在状态框中输入当前时间然后点击发布吗?或者假设我让程序能够从用户那里获取输入(可能使用扫描仪?),然后根据输入,它可以加载谷歌,在搜索栏中输入,然后单击搜索。
问问题
1574 次
1 回答
4
您可以通过使用Selenium来做到这一点:
Selenium 使浏览器自动化。而已。你用这种力量做什么完全取决于你。主要是为了测试目的而自动化 Web 应用程序,但当然不仅限于此。无聊的基于 Web 的管理任务也可以(而且应该!)自动化。
这是文档页面中的示例,该页面在 Google 上搜索“奶酪”一词:
package org.openqa.selenium.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Selenium2Example {
public static void main(String[] args) {
// Create a new instance of the Firefox driver
// Notice that the remainder of the code relies on the interface,
// not the implementation.
WebDriver driver = new FirefoxDriver();
// And now use this to visit Google
driver.get("http://www.google.com");
// Alternatively the same thing can be done like this
// driver.navigate().to("http://www.google.com");
// Find the text input element by its name
WebElement element = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys("Cheese!");
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
// Google's search is rendered dynamically with JavaScript.
// Wait for the page to load, timeout after 10 seconds
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().startsWith("cheese!");
}
});
// Should see: "cheese! - Google Search"
System.out.println("Page title is: " + driver.getTitle());
//Close the browser
driver.quit();
}
}
于 2013-02-27T18:13:32.353 回答