2011-01-09 108 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

相关问题