我对htmlagilitypack有点新。我想用我的HttpWebRequest,它可以返回一个网页的HTML,然后用htmlagilitypack解析这个HTML。我想找到所有div
的特定课程,然后获取这些div
的内部文本。这是我迄今为止所拥有的。我的get请求成功返回网页html:HtmlAgilityPack找不到来自HttpWebRequest的返回HTML的节点
Public Function mygetreq(ByVal myURL as String, ByRef thecookie As CookieContainer)
Dim getreq As HttpWebRequest = DirectCast(HttpWebRequest.Create(myURL), HttpWebRequest)
getreq.Method = "GET"
getreq.KeepAlive = True
getreq.CookieContainer = thecookie
getreq.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:29.0) Gecko/20100101 Firefox/29.0"
Dim getresponse As HttpWebResponse
getresponse = DirectCast(getreq.GetResponse, HttpWebResponse)
Dim getreqreader As New StreamReader(getresponse.GetResponseStream())
Dim thePage = getreqreader.ReadToEnd
'Clean up the streams and the response.
getreqreader.Close()
getresponse.Close()
Return thePage
End Function
该函数返回html。然后我把HTML到这一点:
'The html successfully shows up in the RichTextBox
RichTextBox1.Text = mygetreq("http://someurl.com", thecookie)
Dim htmldoc = New HtmlAgilityPack.HtmlDocument()
htmldoc.LoadHtml(RichTextBox1.Text)
Dim htmlnodes As HtmlNodeCollection
htmlnodes = htmldoc.DocumentNode.SelectNodes("//div[@class='someClass']")
If htmlnodes IsNot Nothing Then
For Each node In htmlnodes
MessageBox.Show(node.InnerText())
Next
End If
的问题是,htmlnodes
是回来为null
。所以最后的If Then
循环将不会运行。它觉得没有什么,但我知道一个事实,这div
和class
存在于HTML页面,因为我可以看到在RichTextBox1的HTML:
<div class="someClass"> This is inner text </div>
到底是什么问题吗? htmldoc.LoadHtml
不喜欢mygetreq
为页面html返回的字符串类型吗?
这和html实体有什么关系吗? thePage
包含<
和>
括号。他们没有实习。
我还看到有人发帖here(C#)使用HtmlWeb
类,但我不知道如何设置它。我的大部分代码已经写入httpWebRequest
。
感谢您的阅读并感谢您的帮助。
一如既往,我建议使用CsQuery而不是HtmlAgilityPack。其中一位SO成员也提到过,一旦尝试过,我不想回去。 – Neolisk
@neolisk从未听说过。我只是不断听到HtmlAgilityPack。任何好的示例代码在那里为我正在尝试做的,你可能已经可用? =) – Micro
同样在这里,我总是在我尝试[CsQuery]之前推荐HtmlAgilityPack(https://github.com/jamietre/CsQuery)。你知道jQuery吗?如果是的话,应该是一个简单的开关。我会尽快为你带来一些例子。 – Neolisk