Html 如何让vb.net从网页中添加特定div类中的所有链接?
这就是网页中的html呈现代码的样子Html 如何让vb.net从网页中添加特定div类中的所有链接?,html,vb.net,Html,Vb.net,这就是网页中的html呈现代码的样子 <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 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>
有几种方法可以从xml或html中提取信息。如果html是有效的xml,则可以将LINQ to xml与XPath查询或LINQ查询语法一起使用,以获取特定信息。否则,如果html不是有效的XML,并且无法解析/加载到
XDocument
,则应查看。下面是一个使用查询获取这三个图像链接的示例(html页面需要首先下载并存储为文件或字符串)
最后,您将在列表
变量中获得html页面中的所有链接,准备以您想要的任何方式显示。上面的XPath查询表达式
表示(从右向左读取):
/a[@href]
:选择元素
具有href
属性并且是..的直接子元素//div[@class='mygallery\u inner']
:一个
元素,具有类属性值=mygallery\u inner
,是根元素的后代(不一定是直接子元素)
http://image.com/29.html
http://image.com/12.html
http://image.com/59.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