【发布时间】:2016-08-26 10:50:49
【问题描述】:
我想做的是在我的浏览器(chrome)中打开一个互联网页面,并获取刚刚用我的 java 应用程序打开的页面的 html 源代码。
我不想获取url的源代码,我想要一个连接浏览器并获取打开页面的html代码的程序。
例如,如果我在浏览器中打开 youtube,我希望我的应用程序获取当前页面的 html 代码(在这种情况下是 youtube 代码)。对不起,如果我的英语不是很好。
【问题讨论】:
我想做的是在我的浏览器(chrome)中打开一个互联网页面,并获取刚刚用我的 java 应用程序打开的页面的 html 源代码。
我不想获取url的源代码,我想要一个连接浏览器并获取打开页面的html代码的程序。
例如,如果我在浏览器中打开 youtube,我希望我的应用程序获取当前页面的 html 代码(在这种情况下是 youtube 代码)。对不起,如果我的英语不是很好。
【问题讨论】:
试试这个:
您必须将 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);
}
}
【讨论】:
你可以这样做:
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
【讨论】: