2016-08-11 343 views
0

我已經創建了可以讀取提供的URL的所有HTML的宏,但是我想從該HTML獲取所有網址。VBA從網頁獲取html網址

Sub GetHTML_Click() 

Dim ie As InternetExplorer 
Dim html As HTMLDocument 
Dim j As Integer 
Set ie = New InternetExplorer 
ie.Visible = True 

url = Cells(1, 2) 

ie.navigate url 

Do While ie.READYSTATE <> READYSTATE_COMPLETE 
Application.StatusBar = "Trying to go to website ..." 
Loop 
Application.StatusBar = " " 
Set html = ie.document 
'Dim htmltext As Collection 
Dim htmltext As String 
htmltext = html.DocumentElement.innerHTML 
'Need to add iURL 
Dim htmlurl As IHTMLElement 
For Each htmlurl In hmtltext 
iurl = htmlurl.toString 
Cells(j, 1).Value = CLng(iurl) 
j = j + 1 
Next 

End Sub 

我試圖實現代碼,以獲取網址,但其給「必選對象錯誤」

任何人都可以請幫助修改這個宏,這將有助於我獲取所有從HTML頁面的URL。

我正在使用www.mini.in網站進行測試。

Mayur。

+0

你要添加到您參考IE對象。工具 - >參考文獻 - >微軟互聯網控制 – winghei

+0

@winghei我已經添加了這個參考,讓我檢查你提供的解決方案。 :) –

回答

0

試試這個:

Dim ie As Object 
Dim html As Object 
Dim j As Integer 
Set ie = CreateObject("InternetExplorer.Application") 
ie.Visible = True 
URL = "google.com" 
ie.Navigate URL 
Do While ie.ReadyState <> READYSTATE_COMPLETE 
Application.StatusBar = "Trying to go to website ..." 
Loop 
Application.StatusBar = " " 
Set html = ie.Document 
'Dim htmltext As Collection 
Dim htmlElements As Object 
Dim htmlElement As Object 
Set htmlElements = html.getElementsByTagName("*") 
For Each htmlElement In htmlElements 
    If htmlElement.getAttribute("href") <> "" Then Debug.Print htmlElement.getAttribute("href") 
Next 
+0

這解決了我的問題我只更新這個代碼中的小東西,所以它可以給我所有的URL在Excel表格。 –

+0

'If htmlElement.getAttribute(「href」)<>「」Then Cells(j,1).Value = htmlElement.getAttribute(「href」)j = j + 1' –