0

所以我试图用java下载一个aspx网页(Roblox)的文本。我的代码如下所示:

URL url;
InputStream is = null;
DataInputStream dis;
String line = "";
try {
    System.out.println("connecting");
    url = new URL("http://www.roblox.com");
    is = url.openStream();  // throws an IOException
    dis = new DataInputStream(new BufferedInputStream(is));

    while ((line = dis.readLine()) != null) {
        System.out.println(line);
    }
} catch (Exception ex) {
    ex.printStackTrace();
} finally {
    try {
        is.close();
    } catch (IOException ioe) {}
}

它适用于 www.roblox.com。但是,当我尝试导航到不同的页面 - http://www.roblox.com/My/Money.aspx#/#TradeCurrency_tab - 它不起作用,只是加载 www.roblox.com 屏幕。

任何人都可以帮助澄清这一点吗?任何帮助,将不胜感激。

4

2 回答 2

0

从 URL 和 # 的使用来看,我怀疑这个页面是使用 javascript 来动态创建页面的。

您可以使用http://seleniumhq.org/之类的东西来模拟 Web 浏览器(包括 cookie),这对于任何类型的动态 Web 内容来说都是一种更可靠的方法。

    // The Firefox driver supports javascript 
    WebDriver driver = new FirefoxDriver();

    // Go to the roblox page
    driver.get("http://www.roblox.com");

    System.out.println(driver.getPageSource());

当然,有很多更好的方法可以通过 Selenium 的 WebDriver API 访问页面元素:http: //selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/WebDriver.html

在一个文件中下载 JAR 和所有 deps:http ://code.google.com/p/selenium/downloads/detail?name=selenium-server-standalone-2.27.0.jar

请注意,您可以通过代码导航到其他页面:http: //seleniumhq.org/docs/03_webdriver.html -

     WebElement link = driver.findElement(By.linkText("Click Here Or Whatever"));
     link.click();

然后

     System.out.println(driver.getPageSource());

将获得下一页的页面文本。

于 2012-12-06T22:35:00.180 回答
0

您在 java 中获得的内容与您在浏览器中看到的内容不同,因为服务器将以下标头添加到响应中:

Location=https://www.roblox.com/Login/Default.aspx?ReturnUrl=%2fMy%2fMoney.aspx

如果存在“Location”标头,您应该从 URLConnection 获取标头的值并手动重定向。据我所知,即使您使用 HttpConnection,您也不会自动重定向到“https”

编辑:

你可以这样做(我删除了其他代码,比如异常处理只是为了专注于重定向,所以不要把它当作正确的“编码”示例):

public static void main(String[] args) throws Exception {
    printPage("http://www.roblox.com/My/Money.aspx#/#TradeCurrency_tab");       
}

public static void printPage(String address) throws Exception {     
    String line = null;
    System.out.println("connecting to:" + address);
    URL url = new URL(address);
    URLConnection conn = url.openConnection();
    String redirectAdress = conn.getHeaderField("Location");
    if (redirectAdress != null) {
        printPage(redirectAdress);
    } else {
        InputStream is = url.openStream(); 
        DataInputStream dis = new DataInputStream(new BufferedInputStream(is));
        while ((line = dis.readLine()) != null) {
            System.out.println(line);
        }
    }
}
于 2012-12-06T23:30:44.173 回答