从指定网站抓取数据时出错

时间:2020-06-14 07:44:30

标签: excel vba object error-handling

我是excel中vba的新手。我设法编写了一个代码,该代码从给定的网站上抓取数据并将其存储在excel工作表中。该代码几乎每次运行时都有效,但有时会出现错误:

对象变量或With块变量未设置。

因此找出原因非常具有挑战性。另外,如果您可以帮助我加快代码的速度(也许不使用剪贴板来对表进行特殊化,但是我不知道该如何使用...)。另外您也知道,如果我单击结束并再次运行该子程序,一旦提示错误,它就会毫无问题地运行。错误在指定的行中被提示(有时,子通常在大多数时间都可以正常工作),并带有以下注释:'这是引发错误的行。我感谢任何类型的帮助人员,在此先感谢您:)。 子看起来像这样:

Sub PaData()
Dim c As Object, D As Object, H As Object, PID$, SD As Date, FC$, cf$

Set c = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
Set D = CreateObject("HTMLFile")
Set H = CreateObject("WinHTTP.WinHTTPRequest.5.1")

FC = "EXA"         ' This is used to generate the website url
cf = VBMa   ' This is another sub which works fine and i need it to get into the webiste

' Get the page
H.SetAutoLogonPolicy 0
H.SetClientCertificate "CURRENT_USER\MY\" & Environ("USERNAME")
H.Open "GET", "https://confidentialwebsite=" & FC
H.setRequestHeader "Cookie", cf
H.Send
H.waitForResponse

' Put the response into the HTML object
D.body.innerHTML = H.ResponseText
' Copy _only a given Table
c.setText D.getElementByID("giventable").outerHTML 'This is the line which throws the error
c.PutInClipBoard

' Paste into the sheet, remove hyperlinks and unMerge all data
Sheets("Pdata").Cells.Delete
Sheets("Pdata").[A1].PasteSpecial
Sheets("Pdata").Cells.Hyperlinks.Delete
Sheets("Pdata").Cells.UnMerge
'update time
Sheets("SM").Range("B1").Value = Sheets("Pdata").Range("D2").Value + 2 / 24

End Sub 

1 个答案:

答案 0 :(得分:0)

对网络服务器执行HTTPRequest时,应始终使用.Status(请参阅:this始终验证此调用的返回状态

可以在以下位置找到可能的状态编号的概述:https://httpstatuses.com/或此处:https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#1xx_Informational_response