【问题标题】:Excel VBA - Web scraping - Track parcel - deal with error where tracking number is incorrectExcel VBA - 网页抓取 - 跟踪包裹 - 处理跟踪号不正确的错误
【发布时间】:2021-01-09 22:33:11
【问题描述】:

我正在尝试创建一个函数,该函数通过使用跟踪号来获取空运单的状态。 在 stackoverflow 社区的帮助下,我设法创建了一个正确获取状态的函数。

但是,我正在尝试添加跟踪号可能不正确的错误处理。 使用当前函数,如果跟踪号有效,它会正确获取结果。 但是当提供的数字不正确时,该函数会返回一个 0 值并在后台循环运行。从 VBA 编辑器停止时,excel 崩溃。

这是迄今为止我想出的代码。任何添加此错误处理的帮助将不胜感激。 样品正确货号:92366691 样品错误货号:59473805

 Function FlightStat_AF(cargoNo As Variant) As String
 Dim url As String, ie As Object, result As String

  url = "https://www.afklcargo.com/mycargo/shipment/detail/057-" & cargoNo

  Set ie = CreateObject("InternetExplorer.Application")
  With ie
    .Visible = False
    .navigate url
    Do Until .readyState = 4: DoEvents: Loop
  End With
  'wait a little for dynamic content to be loaded
  Application.Wait (Now + TimeSerial(0, 0, 1))

  'Get the status from the table
  Do While result = ""
    DoEvents
    On Error Resume Next
     result = Trim(ie.document.getElementsByClassName("fs-12 body-font-bold")(1).innerText)
    On Error GoTo 0
    Application.Wait (Now + TimeSerial(0, 0, 1))
  Loop

  ie.Quit: Set ie = Nothing
  
  'Return value of the function
  FlightStat_AF = result
End Function

【问题讨论】:

    标签: excel vba web-scraping error-handling


    【解决方案1】:

    检查 url 是否有效的方法是使用下面的函数:

    Public Function URLexist(urlToCheck  As String) As Boolean
        'source :  https://excel-malin.com
    
        On Error GoTo Err
    
        Dim oXHTTP As Object
        Set oXHTTP = CreateObject("MSXML2.XMLHTTP")
    
        oXHTTP.Open "HEAD", urlToCheck , False
        oXHTTP.send
    
        URLexist = (oXHTTP.Status = 200)
        Exit Function
    
        Err:
        URLexist = False
    End Function
    

    【讨论】:

    • 嗨杰斯汀。谢谢你的回答。但我是 VBA 和网络抓取的新手。你能告诉我如何将它集成到我现有的功能中吗?
    • 在调用 ie.navigate(url) 之前,你应该测试 url 是否存在: If URLexist(url) Then .....
    【解决方案2】:

    我今天学到了很多,对此我感到非常高兴。我的代码基于这个答案,我从^^
    Scraping specific data inside a table II (Answer by SIM)

    学到了所有新东西

    您询问发送错误 ID 时如何避免错误。这是您如何处理该错误的答案,以及当您以错误的 ID 格式发送 ID 时出现的错误。

    这是Sub()来测试功能:

    Sub test()
      'A valid ID
      MsgBox FlightStat_AF("92366691")
      
      'A wrong ID
      'The whole string is "The provided AWB(s) is either invalid, not found or you are not authorized for it."
      'The function FlightStat_AF cuts the string by comma
      'So it delivers "The provided AWB(s) is either invalid"
      'I'am not clear with regex till now and used it like the macro this code is based on ;-)
      MsgBox FlightStat_AF("59473805")
      
      'Somthing else than a valid ID format
      MsgBox FlightStat_AF("blub")
    End Sub
    

    这是function() 以获得您想要的答案:

    Function FlightStat_AF(cargoNo As Variant) As String
    
      Const url = "https://www.afklcargo.com/mycargo/api/shipment/detail/057-"
      Dim elem As Object
      Dim result As String
      Dim askFor As String
      
      With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", url & cargoNo, False
        .send
        result = .responseText
        
        If .Status = 200 Then
          If InStr(1, result, "faultDescription") = 0 Then
            askFor = """metaStatus"""
          Else
            askFor = """faultDescription"""
          End If
          
          With CreateObject("VBScript.RegExp")
            .Global = True
            .MultiLine = True
            .Pattern = askFor & ":(.*?),"
            Set elem = .Execute(result)
          End With
          
          If Not elem Is Nothing Then
            result = Replace(elem(0).SubMatches(0), Chr(34), "")
          Else
            result = "No Value"
          End If
        Else
          result = "No cargoID"
        End If
      End With
      
      FlightStat_AF = result
    End Function
    

    【讨论】:

    • 找不到匹配项时会发生什么?您可能想在其中添加一个测试,elem is not nothing。
    • @QHarr 你是个很努力的老师 ;-) 没关系 :-) 我以为我已经涵盖了所有可能的情况。有没有给出 VBA 运行时错误的传递参数示例?
    • 我很抱歉 Zwenn。我不想显得卑鄙!我喜欢看你的回答。我经常很懒惰,并不总是把所有好的支票都放进去,但我看到你为支票付出了很多努力。关于您的运行时错误,您是否要求您的代码可能失败的案例?
    • 可能不仅仅是传递的参数有问题,而是正则表达式没有返回匹配项。你可能没问题,但有皮带和牙套。至少你会迎合对 html/page 的更改。虽然很难,但如果按照代码所示输入,您可以将 ByVal 作为字符串传递
    • @QHarr 你对我来说似乎并不刻薄。一切正常 :-) 可能失败的情况是“blub”参数。但我拦截了它。我不知道在函数中引发运行时错误还会发生什么。 (对不起,我也用 SO 来学习更多的英语。所以我的答案来得很慢。)
    猜你喜欢
    • 2019-11-15
    • 1970-01-01
    • 2014-11-09
    • 2015-03-27
    • 2014-05-02
    • 2011-02-19
    • 2013-01-02
    • 2023-04-06
    • 1970-01-01
    相关资源
    最近更新 更多