我制作了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/");
谢谢
最佳答案
您的方法是正确的,但您没有创建绝对 URL。
而不是:
String absHref = link.attr("href"); // "page2.html/"
使用 :
String absHref = link.absUrl("href"); // this wil give you http://example.com/page2.html
剩下的就和你正在做的一样。
http://jsoup.org/apidocs/org/jsoup/nodes/Node.html
不幸的是,Jsoup不是一个网络爬虫,而只是具有直接连接和获取页面能力的解析器。爬行逻辑 - 例如。接下来要获取/访问的内容由您负责实现。您可以在 google 上搜索 Java 的网络爬虫,也许其他的东西会更合适。
关于java - 如何使用 jsoup 输入 url 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34887809/