【发布时间】:2016-01-19 22:02:47
【问题描述】:
我做了2个简单的html页面
第 1 页:
<html>
<head>
</head>
<body>
<a href="page2.html">enter page 2</a>
<p>
some data
</p>
</body>
</html>
第 2 页:
<html>
<head>
</head>
<body>
<a href="page1.html">enter page 1</a>
<a href="page3.html">enter page 3</a>
<p>
some other data
</p>
</body>
</html>
我想使用 jsoup 库获取链接
Document doc = Jsoup.parse(file, "UTF-8", "http://example.com/"); //file = page1.html
Element link = doc.select("a").first();
String absHref = link.attr("href"); // "page2.html/"
现在我想做的是从第 1 页(我的计算机上的本地)进入第 2 页,然后解析它。
我尝试过这样做:
Document doc2 = Jsoup.connect(absHref).get();
但它不起作用,让我 404 错误
编辑:
从@JonasCz 的一个小回放中,我尝试了这个:它正在工作,我只是认为有一个更好、更聪明的方法。
File file = new File(args[0]);
String path = file.getParent() + "\\";
Document doc = Jsoup.parse(file, "UTF-8", "http://example.com/"); //file = page1.html
Element link = doc.select("a").first();
String Href = link.attr("href"); // "page2.html/"
File file2 = new File(path+href);
Document doc2 = Jsoup.parse(file2, "UTF-8", "http://example.com/");
谢谢
【问题讨论】:
-
您可以创建一组绝对href,并仅解析/访问那些您仍然可以添加到集合中的内容。
标签: java web-crawler jsoup