【问题标题】:Got results in one pc but encountered `Run-time error 438` in another pc even when I used the same script在一台电脑上得到结果,但在另一台电脑上遇到“运行时错误 438”,即使我使用相同的脚本
【发布时间】:2021-05-20 03:07:46
【问题描述】:

我创建了一个脚本来解析 recipe 名称和 serving 来自这样的 links。当我在两台不同的计算机上运行相同的脚本时,我在一台计算机上得到了预期的结果,但是我遇到了这个错误运行时错误 438(对象不支持这个属性或方法) 在另一台计算机上。该脚本在下面的脚本中抛出指向这一行 Servings = .Item(I).NextSibling.innerText 的错误。

errors out的那台电脑的excel版本、操作系统和位 Excel 2019, windows 10, 64bit

finds success的那台电脑的excel版本、操作系统和位 Excel 2013, windows 7, 32bit

这是我使用的脚本:

Public Sub FetchRecipeInfo()
    Dim Http As Object, Html As HTMLDocument, Servings$, R&
    Dim Url As Variant, linkList As Variant, I&, Ws As Worksheet
    
    Set Html = New HTMLDocument
    Set Http = CreateObject("MSXML2.XMLHTTP")
    Set Ws = ThisWorkbook.Worksheets("Sheet1")
    R = 1

    linkList = Array( _
        "https://www.allrecipes.com/recipe/18871/easy-tuna-casserole/", _
        "https://www.allrecipes.com/recipe/21791/tuna-noodle-casserole-iv/" _
       )

    For Each Url In linkList
        With Http
            .Open "GET", Url, False
            .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36"
            .send
            Html.body.innerHTML = .responseText
        End With
        
        Ws.Cells(R, 1) = Html.querySelector("h1.headline").innerText

        With Html.querySelectorAll(".recipe-meta-item-header")
            For I = 0 To .Length - 1
                If InStr(.item(I).innerText, "Servings:") > 0 Then
                    Servings = .item(I).NextSibling.innerText
                    Ws.Cells(R, 2) = Servings
                    Exit For
                End If
            Next I
        End With
        R = R + 1
    Next Url
End Sub

预期输出:

Easy Tuna Casserole 8

为什么我在一台电脑上得到结果,但在另一台电脑上遇到Run-time error 438,即使我使用相同的脚本?

【问题讨论】:

  • 可能另一台PC没有Mozilla版本更新,因此您的xml解析格式不同或为空?

标签: vba web-scraping


【解决方案1】:

我不知道为什么它可以在另一台机器上运行。我假设与底层解析器有关。使用我的设置(Microsoft® Excel® 2019 MSO (16.0.13929.20206) 32 位 Windows 10 MSHTML.dll 11.00.19041.985),有一个文本节点作为直接相邻的兄弟节点,它没有 .innerText 属性,但你可以使用.nodeValue。相反,我认为您想继续下一个兄弟姐妹,即

Servings = .Item(I).NextSibling.NextSibling.innerText

这适用于 Windows 10 64 位。所以,如果这个新行在你的 Win 7 上失败了,那么在基于版本的 If Else 中换行。

【讨论】:

  • 它在 excel 2013 中工作 .item(I).NextSibling.innerText,但是当我尝试这个 .Item(I).NextSibling.NextSibling.innerText 时失败了。
  • 包装一个 If Else 我猜基于版本。似乎有什么不同,中间文本节点的存在/不存在/它在解析器中处理。
  • 尝试在两台机器上打印出 item(n).outerHTML 并进行比较。
  • 感谢一万亿您的大力支持。这件事MSHTML.IHTMLDOMChildrenCollection 对我来说完全陌生,直到你在上面创建了自己的帖子..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-21
  • 2012-09-06
  • 2014-09-15
  • 2023-04-07
  • 2021-11-01
  • 2014-07-08
  • 1970-01-01
相关资源
最近更新 更多