2014-01-25 57 views
0

這就是HTML代碼的網頁渲染代碼看起來像如何讓vb.net從網頁中添加特定div類中的所有鏈接?

<div class="mygallery_entry"> 
<div class="mygallery_inner"> 
<a title="img1" class="gallery_image" href="http://image.com/29.html"><img src="/mini/1.jpg" alt="" height="208" width="333" border="0"></a> 
</div> 
<div class="mygallery_inner"> 
<a title="img2" class="gallery_image" href="http://image.com/12.html"><img src="/mini/2.jpg" alt="" height="208" width="333" border="0"></a> 
</div> 
<div class="mygallery_inner"> 
<a title="img3" class="gallery_image" href="http://image.com/59.html"><img src="/mini/3.jpg" alt="" height="208" width="333" border="0"></a> 
</div> 
</div> 

我的輸出變爲列表框,它應該是這樣的:

http://image.com/29.html 
http://image.com/12.html 
http://image.com/59.html 

回答

0

有幾種方法來提取XML信息或者html。如果html是一個有效的xml,那麼可以使用帶有XPath查詢或LINQ查詢語法的LINQ-to-XML獲取特定信息。否則,如果html不是有效的XML並且無法解析/加載到XDocument,則應該查看Html Agility Pack。下面是使用XPath查詢得到這三個圖像鏈接(html頁面需要首先下載並存儲爲文件或作爲字符串)的示例。

Imports System.Xml.XPath 
.... 
Dim doc = XDocument.Parse(htmlString) 
'if you want to load from html file instead of string, use XDocument.Load as follow 
'Dim doc = XDocument.Load(pathToHtmlFile) 
Dim list = New List(Of String)() 
For Each a As XElement In doc.XPathSelectElements("//div[@class='mygallery_inner']/a[@href]") 
    list.Add(a.Attribute("href").Value) 
Next 

最終你會得到來自HTML頁面中的所有鏈接list變量,準備在任何你想要的顯示。上述 裝置XPath查詢表達式(從右到左讀):

  1. /a[@href]:選擇元件<a>具有href屬性,並且是直接子..
  2. //div[@class='mygallery_inner']:具有class屬性值的<div>元素= mygallery_inner並且是根元素的後代(不一定是直接的孩子)
相關問題