使用Java从网页中提取数据?
我正在尝试用Java创建我的第一个程序。 目标是编写一个浏览网站并为我下载文件的程序。 但是,我不知道如何使用Java与互联网进行交互。 谁能告诉我哪些主题可以查找/阅读或推荐一些好的资源?
最简单的解决方案(不依赖于任何第三方库或平台)是创建指向您要下载的网页/链接的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教程的网络章节 ,包括使用URL
- 让自己更轻松: Apache HttpComponents (包括HttpClient)
轻松粘合和缝合的东西
您始终可以使用exec()
和类似方法从Java调用外部工具。 例如,您可以使用wget
或cURL
。
铁杆的东西
然后,如果你想进入更成熟的东西,谢天谢地,需要自动化的网络测试,因为我们为此提供了非常实用的工具。 看着:
- HtmlUnit (function强大且简单)
- selenium , selenium-RC
- WebDriver / Selenium2 (仍在开发中)
- JBehave与JBehave Web
其他一些库是有目的地编写网络报废:
- JSoup
- 短程游览
一些解决方法
Java是一种语言,但也是一个平台,其上运行着许多其他语言。 其中一些集成了很好的语法糖或库来轻松构建scrappers。
查看:
- Groovy (和它的XmlSlurper )
- 或Scala ( 这里和这里提供了很好的XML支持)
如果你知道一个很棒的Ruby库( JRuby ,有一篇关于使用JRuby和HtmlUnit的文章 )或Python ( Jython ),或者你更喜欢这些语言,那么就给它们的JVM端口一个机会。
一些补充
其他一些类似的问题:
- 使用Java从HTML中抓取数据
- HTML Scraping的选项
这是我使用URL
的解决方案,并try with resources
短语来捕获exception。
/** * Created by mona on 5/27/16. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; public class ReadFromWeb { public static void readFromWeb(String webURL) throws IOException { URL url = new URL(webURL); InputStream is = url.openStream(); try( BufferedReader br = new BufferedReader(new InputStreamReader(is))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (MalformedURLException e) { e.printStackTrace(); throw new MalformedURLException("URL is malformed!!"); } catch (IOException e) { e.printStackTrace(); throw new IOException(); } } public static void main(String[] args) throws IOException { String url = "https://madison.craigslist.org/search/sub"; readFromWeb(url); } }
您还可以根据需要将其保存到文件中,或使用XML
或HTML
库进行解析。