HtmlAgilityPack干扰我的代码(不是HtmlAgilityPack问题)

时间:2010-09-13 00:39:38

标签: vb.net html-agility-pack

以下是我的代码片段:

 Dim content As String = ""
    Dim web As New HtmlAgilityPack.HtmlWeb
    Dim doc As New HtmlAgilityPack.HtmlDocument()
    doc.Load(WebBrowser1.DocumentStream)
    Dim hnc As HtmlAgilityPack.HtmlNodeCollection = doc.DocumentNode.SelectNodes("//div[@class='address']/preceding-sibling::h3[@class='listingTitleLine']")
    For Each link As HtmlAgilityPack.HtmlNode In hnc
      Dim replaceUnwanted As String = ""
      replaceUnwanted = link.InnerText.Replace("&", "&") '
<span style="white-space:pre"> </span>  content &= replaceUnwanted & vbNewLine
    Next
'I have a bunch of code here I removed ------------------------------
      Dim htmlDoc As HtmlDocument = Me.WebBrowser2.Document
      Dim visibleHtmlElements As HtmlElementCollection = htmlDoc.GetElementsByTagName("TD")
      Dim found As Boolean = False
      For Each str As HtmlElement In visibleHtmlElements
        If Not String.IsNullOrEmpty(str.InnerText) Then
          Dim text As String = str.InnerText
          If str.InnerText.Contains(parts(2)) Then
            found = True
          End If
        End If
      Next

我收到 Me.WebBrowser2.Document 的错误:

“类型'System.Windows.Forms.HtmlDocument'的值无法转换为'HtmlAgilityPack.HtmlDocument'。

另一个 htmlDoc.GetElementsByTagName

'GetElementsByTagName'不是'HtmlAgilityPack.HtmlDocument'的成员。

当我没有使用HAP时,代码工作,但我需要导入它来做某事,现在它干扰了这个。请帮助。

1 个答案:

答案 0 :(得分:3)

问题是HtmlAgilityPackSystem.Windows.Forms都有一个名为HtmlDocument的类型。

你可能只需要解决这一行:

' Here the VB compiler must think you mean HtmlAgilityPack.HtmlDocument: '
Dim htmlDoc As HtmlDocument

...将其改为:

Dim htmlDoc As System.Windows.Forms.HtmlDocument

general 中,解决此类问题的一个好方法是使用Imports语句为名称冲突的类型提供别名,如下所示:

Imports AgilityDocument = HtmlAgilityPack.HtmlDocument
Imports FormsDocument = System.Windows.Forms.HtmlDocument

然后,您将在代码中使用其中一个别名,而不是键入共享名称。所以,例如:

Dim doc As New AgilityDocument
Dim htmlDoc As FormsDocument = Me.WebBrowser2.Document