java从网页抓取数据(我正在尝试用Java编写我的第一个程序。)

优采云 发布时间: 2022-03-21 17:02

  java从网页抓取数据(我正在尝试用Java编写我的第一个程序。)

  我正在尝试用 Java 编写我的第一个程序。目标是编写一个浏览到 网站 并为我下载文件的程序。但是,我不知道如何使用 Java 与互联网交互。谁能告诉我要寻找/阅读哪些主题或推荐一些好的资源?

  最佳答案

  最简单的解决方案(不依赖于任何第 3 方库或平台)是创建指向您要下载的网页/链接的 URL 实例,并使用流来读取内容。

  例如:

  import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.net.URL;

import java.net.URLConnection;

public class DownloadPage {

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

// Make a URL to the web page

URL url = new URL("http://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage");

// Get the input stream through URL Connection

URLConnection con = url.openConnection();

InputStream is =con.getInputStream();

// Once you have the Input Stream, it's just plain old Java IO stuff.

// For this case, since you are interested in getting plain-text web page

// I'll use a reader and output the text content to System.out.

// For binary content, it's better to directly read the bytes from stream and write

// to the target file.

BufferedReader br = new BufferedReader(new InputStreamReader(is));

String line = null;

// read each line and write to System.out

while ((line = br.readLine()) != null) {

System.out.println(line);

}

}

}

  希望这可以帮助。

  使用Java从网页中提取数据?,我们在 Stack Overflow 上发现了一个类似的问题:

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线