【问题标题】:Get html code from an internet page opened in my browser从我的浏览器中打开的互联网页面获取 html 代码
【发布时间】:2016-08-26 10:50:49
【问题描述】:

我想做的是在我的浏览器(chrome)中打开一个互联网页面,并获取刚刚用我的 java 应用程序打开的页面的 html 源代码。

我不想获取url的源代码,我想要一个连接浏览器并获取打开页面的html代码的程序。

例如,如果我在浏览器中打开 youtube,我希望我的应用程序获取当前页面的 html 代码(在这种情况下是 youtube 代码)。对不起,如果我的英语不是很好。

【问题讨论】:

标签: java url browser


【解决方案1】:

试试这个:

您必须将 URL 作为参数传入,您将获得 HTML 代码

  public static void main(String[] args) throws IOException {
      URL u = null;
      try {
          u = new URL(args[0]);
      } catch (MalformedURLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
      }

      BufferedReader in = new BufferedReader(new InputStreamReader(u.openStream()));
      String line = null;
      while((line = in.readLine()) != null){
          System.out.print(line);
      }
  }

【讨论】:

【解决方案2】:

你可以这样做:

import java.util.*;
public static void main(String[] args) {  
    Scanner input = new Scanner(System.in);
    URL url;
    InputStream is = null;
    BufferedReader br;
    String line;

    try {
        String urlInput = input.nextLine();
        url = new URL(urlInput);
        is = url.openStream();  // throws an IOException
        br = new BufferedReader(new InputStreamReader(is));

        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    } catch (MalformedURLException mue) {
        mue.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        try {
            if (is != null) is.close();
        } catch (IOException ioe) {
            // nothing to see here
        }
    }
}

我从这里得到这个:How do you Programmatically Download a Webpage in Java

【讨论】:

  • 用这个代码确定我用程序打开一个网页并下载在控制台中编写的url的源代码,但我想做的是(自己)打开一个网页,并下载代码而不考虑 url 页面,我希望我的程序连接到浏览器窗口并下载其中打开的互联网页面的 html
猜你喜欢
  • 1970-01-01
  • 2020-12-14
  • 2021-09-08
  • 2023-03-26
  • 2016-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-14
相关资源
最近更新 更多