2013-01-18 17 views
1

正如問題所述;是否有一些方法可以檢測PHP頁面內的所有URL,如果它們是相對的。 並考慮當然是包含在PHP頁面的URL可能出現在不同的行爲:如何檢測HTML網頁中的所有相對URL?

<link rel="stylesheet" href="/lib/css/hanv2/ie.css" /> 
<img src="/image.jpg"> 
<div style="background-image: url(/lib/data/emotion-header-v2/int-algemeen08.jpg)"></div> 

,所以我需要得到相對URL不管是它的bihavior css linkjs linkimage linkswf link

我使用AgilityPack對於這一點,這裏是一些C#代碼snippest我用來檢測環節,檢查他們是否是相對的:

 // to extract all a href tags 
private List<string> ExtractAllAHrefTags(HtmlAgilityPack.HtmlDocument htmlSnippet) 
    { 
     List<string> hrefTags = new List<string>(); 

     foreach (HtmlNode link in htmlSnippet.DocumentNode.SelectNodes("//link[@href]")) 
     { 
      HtmlAttribute att = link.Attributes["href"]; 
      hrefTags.Add(att.Value); 
     } 

     return hrefTags; 
    } 


    // to extract all img src tags 
    private List<string> ExtractAllImgTags(HtmlAgilityPack.HtmlDocument htmlSnippet) 
    { 
     List<string> hrefTags = new List<string>(); 

     foreach (HtmlNode link in htmlSnippet.DocumentNode.SelectNodes("//img[@src]")) 
     { 
      HtmlAttribute att = link.Attributes["src"]; 
      hrefTags.Add(att.Value); 
     } 

     return hrefTags; 
    } 




     //to check whether path is relative  
      foreach (string s in AllHrefTags) 
      {     
       if (!s.StartsWith("http://") || !s.StartsWith("https://")) 
       { 
        // path is not relative 
       } 
      } 

我不知道是否有一個好的或更準確方式使用AgilityPack或者在短的路東西

+0

HtmlAgility包不能正確地解析PHP源代碼,即使它會不合理地包含呈現的鏈接...你確定你需要解析PHP,但不是由一些服務器端代碼生成的HTML(這可能是PHP )? –

+0

Thankyou - 更正了標題:) –

回答

2

您可以使用此XPath表達式來提取相對於得到一個給定的HTML頁面的所有相對路徑從HTML頁面網址指向的href或SRC值:

htmlSnippet.DocumentNode.SelectNodes("(//@src|//@href)[not(starts-with(.,'http://'))][not(starts-with(.,'https://'))]"); 

你可能要篩選與#至極開始被用來跳轉到一個特定的位置在當前頁面上,(例如鏈接:< A HREF = 「#tips」>):

htmlSnippet.DocumentNode.SelectNodes("(//@src|//@href)[not(starts-with(.,'http://'))][not(starts-with(.,'https://'))][not(starts-with(.,'#'))]"); 
相關問題