2011-01-09 187 views
6

我有一個程序,它從Excel文件中提取數據併爲用戶操作它。但爲了獲得更新的Excel文件,他們需要從網站下載。我最初嘗試使用機器人類導航到網站,使用用戶名和密碼登錄,然後導航到網站的正確部分,並找到「下載Excel電子表格」按鈕並點擊它。但我明白這是一種可怕的做法,並不總是奏效。 什麼是更好的方式,我可以做到這一點,這樣我的程序就可以進入網站並導航到我想要的頁面,然後下載數據。我讀到了'網頁報廢',但我認爲這不會允許我這樣做。我真的很想與網頁互動,而不是下載它的內容。任何幫助都會很棒。 謝謝, 彼得如何使Java應用程序與網站進行交互

+0

是否該網站提供您可以改用不必通過提交按鈕得到它的API。 – 2011-01-09 20:56:12

回答

12

如果你確實需要與互動該網站然後硒/ webdriver是完美的爲您的需求:

http://code.google.com/p/selenium/wiki/GettingStarted

樣品谷歌搜索:

package org.openqa.selenium.example; 

import org.openqa.selenium.By; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.htmlunit.HtmlUnitDriver; 

public class Example { 
    public static void main(String[] args) { 
     // Create a new instance of the html unit driver 
     // Notice that the remainder of the code relies on the interface, 
     // not the implementation. 
     WebDriver driver = new HtmlUnitDriver(); 

     // And now use this to visit Google 
     driver.get("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()); 
    } 
} 
0

如果您知道URL,您可以使用http請求下載文件。快速谷歌發現這一點:http://download.oracle.com/javase/tutorial/networking/urls/readingWriting.html下載文件並保存到磁盤

+0

謝謝,我保存了未來的鏈接,但我需要下載的鏈接沒有直接鏈接,我可以在沒有首先登錄網站的情況下獲得。所以我需要更多的方式來與網站互動,所以我可以登錄並獲得鏈接 – Peter 2011-01-09 18:49:56

+0

有問題的網站是否提供任何類型的API來做到這一點?如果不是,刮除是真正的唯一選擇,除了使用你的機器人解決方案(其中,正如你所說,非常可怕:) – 2011-01-09 19:07:03

相關問題