2015-12-27 68 views
0

我想從html文檔讀取所有網址。JSObject到JSArray

我使用以下代碼:

Dim html As String = 
            "var linksArray = new Array(); " & 
            "for (var i = 0; i < document.links.length; i++) {" & 
            "linksArray[i] = [String(document.links[i].innerHTML), String(document.links[i].innerText), String(document.links[i].href)];" & 
            "} " & 
            "return linksArray;" 

    Try 
     Dim linksArray As JSObject = _Browser.WebView.EvalScript(String.Format("(function(){{ {0} }})()", html)) 

     If linksArray Is Nothing Then 
      Stop 'this line is not reached, so it should be fine so far 
     End If 

     'the following line throws an error 
     Dim urls As JSArray = linksArray.ToArray() 

     For Each link As JSObject In urls 
      Dim sInnerHTML As String = link(0).ToString().Trim() 
      Dim sInnerText As String = link(1).ToString().Trim() 
      Dim sHRef As String = link(2).ToString().Trim() 

      If sHRef <> "undefined" Then 

       Dim nItem As New clsURL 
       nItem.HRef = sHRef 
       nItem.InnerHTML = sInnerHTML 
       nItem.InnerText = sInnerText 

       nList.Add(nItem) 
      End If 

     Next 
    Catch ex As Exception 
     Debug.Print(ex.Message.ToString) 
     Stop 
    End Try 

然而,線

Dim urls As JSArray = linksArray.ToArray() 

引發錯誤「的對象引用未設置爲對象實例」。

有人知道如何正確地做到這一點嗎?

謝謝!

enter image description here

enter image description here

+0

當您監視 「linksArray」 你看到了什麼? – etalon11

+0

@ etalon11我爲我的帖子添加了截圖。 – AntonioC

+0

你可以請監視一個項目?另外「urls」沒有被聲明爲一個數組。你不能將正常的數組轉換爲JSArray,或? – etalon11

回答

0

明白了:

 Dim linksArray As JSArray = _Browser.WebView.EvalScript(String.Format("(function(){{ {0} }})()", html)) 

     For Each obj As Object In linksArray 

      Dim sInnerHTML As String = obj(0).ToString().Trim() 
      Dim sInnerText As String = obj(1).ToString().Trim() 
      Dim sHRef As String = obj(2).ToString().Trim() 

     Next