我想使用 jsoup 抓取存储在计算机上的网页。问题是我在网站的第一页上找到了所有链接。
示例:Jsoup.parse(C:/Users/MuhammadNaeem/Downloads/Compressed/IRWS_Main_Assignment/literature.offline/authors/carroll-lewis/index.html,"UTF-8");
for(Element x: doc.getElementsByTag("a")){
System.out.println("OUTLINK -> "+x.attr("href"));
}
第一个问题我只需要离线存储的链接。
但是我面临的问题是离线链接的href不完整,我无法继续爬行。 这是我得到的 href 之一。
alices-adventures-in-wonderland/index.html
有什么方法可以自动定向和解析这些离线链接。我不知道我很困惑。
因为为了通过 Jsoup 解析,我需要一个用于离线页面的文件。以及我从第一页获得的路径或不完整的进一步爬行路径。
我的 WebCrawler 类代码如下。
import java.io.File;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
public class MyCrawler {
String s;
public static Document doc =null;
public static File input=null;
static String u="C:/Users/MuhammadNaeem/Downloads/Compressed/IRWS_Main_Assignment/literature.offline/authors/carroll-lewis/";
public static void main(String[] args) throws IOException {
check(u,true);
}
public static void check(String url,boolean c){
try {
if(c==true){
File input=new File(u+"index.html");
doc = Jsoup.parse(input,"UTF-8");
}
else{
File input=new File(u+url);
doc = Jsoup.parse(input,"UTF-8");
//System.out.println(doc);
}
for(Element x: doc.getElementsByTag("a")){
try{
Jsoup.connect(x.attr("href"));
System.out.println("OUTLINK -> "+x.attr("href"));
}
catch(Exception e){
if(x.attr("href").equals("index.html")==true || x.attr("href").equals("index-2.html")==true || x.attr("href").contains("../") ==true ){
}
else{
System.out.println("Offline Link -> "+x.attr("href"));
check(x.attr("href"),false);
}
}
}
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
最佳答案
以下三个要点将帮助您解决问题:
1) 将相对url解析为绝对url
您可以利用 Jsoup 的功能将相对 url 解析为绝对 url。但是,您需要显式指定基本 URI。
因此,当您解析离线页面时,请这样做:
File input = ...
Document doc = Jsoup.parse(input, "UTF-8", "file:///" + input.getAbsolutePath());
// Note the file protocol used for base URI----^
2) 检查链接是否离线
我们将使用 JDK URI用于检查给定链接是否离线的类。
当您在解析的页面中找到链接时,以下是如何检查它们是否离线:
for (Element x : doc.getElementsByTag("a")) {
URI uri = URI.create(x.absUrl("href"));
boolean isOffline = uri.getScheme().equalsIgnoreCase("file");
if (isOffline) {
System.out.println("Offline Link -> " + x.attr("href"));
// ...
}
}
3) 将离线链接转换为绝对文件路径
这里我们将使用File类(class)。检查下面的示例代码:
URI uri = ...
String absolutePath = new File(uri.getPath()).toString();
关于java - 如何用Jsoup爬取离线网页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34537336/