如何查看URL的状态?

2024-03-12

我创建了一个宏,可以在其中从任何网页获取每个 URL。

现在,我在列中包含了每个 URL。

如何检查 URL 是否有效。

如果这些 URL 中的任何一个不起作用,那么它应该在下一列中的 URL 旁边显示错误“不起作用”。

下面是我写的代码:

Sub CommandButton1_Click()
Dim ie As Object
Dim html As Object
Dim j As Integer
j = 1
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = True
url = "www.mini.co.uk"
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")
    If htmlElement.getAttribute("href") <> "" Then Cells(j, 1).Value = htmlElement.getAttribute("href")
    j = j + 1
Next

ActiveSheet.Range("$A$1:$A$2752").removeDuplicates Columns:=1, Header:=xlNo

End Sub

此代码用于从网页中获取 URL。

下面是检查 URL 状态(是否有效)的代码。

Sub CommandButton2_Click()
Dim k As Integer
Dim j As Integer
k = 1
j = 1
'Dim Value As Object
'Dim urls As Object
'urls.Value = Cells(j, 1)

For Each url In Cells(j, 1)
    Dim ie As Object
    Set ie = CreateObject("InternetExplorer.Application")
    ie.Visible = False
    url = Cells(j, 1)
    ie.navigate url

    Do While ie.READYSTATE <> READYSTATE_COMPLETE
        Application.StatusBar = "checking the Data. Please wait..."
    Loop

    Cells(k, 2).Value = "OK"
    'Set html = ie.document
    ie.Quit
    j = j + 1
    k = k + 1
Next

End Sub

由于您有兴趣知道链接是否有效,因此 xmlhttp 可能是一种解决方案。

Set sh = ThisWorkBook.Sheets("Sheet1")
Dim column_number: column_number = 2

'Row starts from 2
For i=2 To 100
    strURL = sh.cells(i,column_number)
    sh.cells(i, column_number+1) = CallHTTPRequest(strURL)
Next


Function CallHTTPRequest(strURL)
    Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")
    objXMLHTTP.Open "GET", strURL, False
    objXMLHTTP.send
    status = objXMLHTTP.Status
    'strContent = ""

    'If objXMLHTTP.Status = 200 Then
    '   strContent = objXMLHTTP.responseText
    'Else
    '   MsgBox "HTTP Request unsuccessfull!", vbCritical, "HTTP REQUEST"
    '   Exit Function
    'End If
    Set objXMLHTTP = Nothing
    CallHTTPRequest = status
End Function
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何查看URL的状态? 的相关文章