2013-02-27 85 views
3

昨天我發佈了這個Retrieving Data in Java。我很好奇,可以在Web瀏覽器打開的情況下運行java程序,然後讓它在網站上運行。如果我在瀏覽器上打開了Facebook,是否可以在狀態框中輸入當前時間,然後點擊發布?或者讓我們說我讓程序能夠從用戶那裏接受輸入(也許使用掃描儀?),然後根據輸入,它可以加載谷歌,將它鍵入搜索欄,然後單擊搜索。Java在網站上執行操作

+0

肯定。聽起來就像你會想要使用提到的網站的API來做「在後臺」的工作。 – 2013-02-27 18:11:58

+0

這聽起來像網頁瀏覽器自動化 – Val 2013-02-27 18:12:50

回答

4

您可以通過使用Selenium做到這一點:

硒自動化的瀏覽器。而已。你用這種力量做的事情完全取決於你。主要是爲了測試目的自動化web應用程序 ,但肯定不僅限於此。 無聊的基於Web的管理任務也可以(也應該)也自動化爲 。

這是例如,從documentation page其搜索在谷歌的「奶酪」一詞:

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(); 
    } 
}