有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

eclipse在Java中保存来自Amazon的页面源代码

我试图保存一个来自亚马逊的页面源代码,这样我就可以看到一个项目的价格。当我试图将其保存到文件中时,它只保存了大约60行,其中大部分是空白。我可以从浏览器中看到源代码,它有数千行。它适用于我试图搜索的任何页面。以下是我尝试的链接:http://www.amazon.com/gp/product/B015WCV70W/ref=s9_simh_gw_g147_i2_r?ie=UTF8&fpl=fresh&pf_rd_m=ATVPDKIKX0DER&pf_rd_s=desktop-2&pf_rd_r=0XHXJAF2NQ35BP5Y435K&pf_rd_t=36701&pf_rd_p=dc68ddd1-99ac-45e5-8c23-e9e0811a2b2c&pf_rd_i=desktop

有更简单的方法吗

这是我的代码:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;


public class DownloadPage {

    public static final Scanner in = new Scanner(System.in);

    public static void main(String[] args) throws IOException {

        System.out.print("Enter URL: ");
        savePage(in.nextLine());

    }

    static void savePage(String entURL) throws IOException{
        URL url = new URL(entURL);
        URLConnection con = url.openConnection();
        InputStream is = con.getInputStream();

        BufferedWriter bw = new BufferedWriter(new FileWriter("text.txt"));
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        int count = 0;
        while (br.ready()) {
            bw.write(br.readLine());
            bw.newLine();
            count++;
        }
        line = null;
        bw.close();
        System.out.println("wrote successfully " + count);
    }
}

抱歉,如果我没有正确格式化,这是我的第一篇帖子


共 (2) 个答案

  1. # 1 楼答案

    这是因为你使用br。ready(),所以每次网络暂停都会导致周期结束 这个块给了我20632行html

    int count = 0;
    while (true) {
        String line = br.readLine();
        if (line == null) {
            break;
        }
        bw.newLine();
           count++;
    }
    
  2. # 2 楼答案

    url只是javascript应用程序的加载点,它将HTML呈现到浏览器中

    如果您想捕获呈现的页面,请尝试模拟浏览器的Selenium/WebDriver(并将运行javascript应用程序)