2014-11-05 88 views
2

下面是一个实例。如果您转到http://superior.edu.pk的源代码(Ctrl + U),您将看到没有基本URL和/或http-equi等。当您向下滚动以检查图像时,它将显示不同的URL以完成相对路径以及何时您将检查HTML网址(例如搜索AdmissionSchedule.aspx),您将看到不同的URL解析相对路径。我的问题是:我如何才能将这些相对URL作为绝对URL?我试过jsoup abd:hre和element.absUrl(“href”);都给我空串。设置document.setBaseUri(“http://www.example.com”);也就是说,由于存在两个用作基本URL的不同URL,因此也不起作用。如何从网页的HTML中获取绝对网址

任何帮助将为我感激。

谢谢

回答

1

你为什么说有两个基本的URL?所有相关链接指向http://superior.edu.pk/presentation/user/(否则!)。

试试下面的代码:

//If you use an URL you haven't to especify base URL 
    Document doc=Jsoup.connect("http://superior.edu.pk/presentation/user/Default.aspx").get(); 
    //If you use a file or a String you have. Base URL is http://superior.edu.pk/presentation/user/ of course 
    //Document doc = Jsoup.parse(Main.class.getResourceAsStream("page.htm"), "utf-8", "http://superior.edu.pk/presentation/user/"); 

    //Only as an example. You can fetch any anchor as wou wish. 
    Elements links = doc.select("div.footerMaterial > a"); 
    for (Element link : links){ 
     String attr = link.absUrl("href"); 
     System.out.println(attr); 
    } 

你会看到所有的正确绝对URL。从相对链接指向所获得的那些,以superior.edu.pk和绝对的人指出他们respectives域(www.digitallibrary.edu.pk和www.google.com)

(编辑)

你还可以测试这个代码:

Element link = doc.select(".logo > a:nth-child(1) > img:nth-child(1)").first(); 
    String attr = link.absUrl("src"); 
    System.out.println(attr); 

会给你:

http://superior.edu.pk/images/logo.jpg 

这是正确的!

解释是相对网址是../../images/logo.jpg,这是http://superior.edu.pk/presentation/user/../../images/logo.jpg,它解析为http://superior.edu.pk/images/logo.jpg

一个页面只能有一个基础url!

+0

例如如果您选中“../../images/logo.jpg”,它会解析为http://www.superior.edu.pk/images/logo.jpg,并且在此处看不到“/ presentation/user /” URL。这就是为什么我说相对URL是用2个基本URL解决的。 – 2014-11-08 10:50:42

+0

好.. ../../images/logo.jpg是相对于superior.edu.pk/presentation/user/也!检查它:http://superior.edu.pk/presentation/user/../../images/logo.jpg – fonkap 2014-11-08 10:58:23

+0

@ user2866518我编辑了答案 – fonkap 2014-11-09 19:04:03