首页 > 解决方案 > 将python try-except(或try-catch)代码块转换为基本excel-selenium应用程序的VBA

问题描述

我有一个代码块;

#Same code in Python
    try:
        io = myElm.get_attribute("rel")
        print(io)
    except IndexError:
        d_io = myElm.get_attribute("data-outcome")
        print(d_io)
    except:
        print("undefined error")

我正在使用硒。当我搜索它时,互联网说没有 try-cath 或 try-expect 方法 VBA。您可以使用 On Error GoTo 方法。

我的目的是,有一个元素。有时它没有“rel”属性,它返回一个错误。所以如果有“rel”属性。我会接受它,如果没有,我会接受“数据结果”属性。上面的代码在 python 中完美运行。

我在互联网上的研究可以转换的代码如下。

唯一的问题,当我使用 GoTo 语句时。我无法回到我离开的地方。我试过像Resume Next smh 一样。它没有用。也许我做不到。顺便说一句,我仅用于应用程序,只是 VBA 的新手。使用 GoTo 方法后有没有办法返回。由于无法返回,因此当我转到 goto 语句时,使用“rel”属性创建的值会发生变化。无论如何,基本上我有 3 个陈述,例如;

On Error GoTo C1
If baglan.IsElementPresent(By.Css(myElm)) Then
Cells(sonsatir, 4) = baglan.FindElementByCss(myElm).Attribute("rel")
Else
Cells(sonsatir, 4) = baglan.FindElementByCss(myElm).Attribute("data-outcome")
End If


On Error GoTo C2
If baglan.IsElementPresent(By.Css(myElm)) Then
Cells(sonsatir, 5) = baglan.FindElementByCss(myElm).Attribute("rel")
Else
Cells(sonsatir, 5) = baglan.FindElementByCss(myElm).Attribute("data-outcome")
End If


On Error GoTo C3
If baglan.IsElementPresent(By.Css(myElm)) Then
Cells(sonsatir, 6) = baglan.FindElementByCss(myElm).Attribute("rel")
Else
Cells(sonsatir, 6) = baglan.FindElementByCss(myElm).Attribute("data-outcome")
End If

'Some codes here'

 C1:
 Cells(sonsatir, 4) = baglan.FindElementByCss(myElm).Attribute("data-outcome")

 C2:
 Cells(sonsatir, 5) = baglan.FindElementByCss(myElm).Attribute("data-outcome")

 C3:
 Cells(sonsatir, 6) = baglan.FindElementByCss(myElm).Attribute("data-outcome")

标签: pythonexcelvbaseleniumweb-scraping

解决方案


仅使用Resume而不是Resume Next.

Resume回到发生错误的地方。

Resume Next错误发生后跳转到下一行。


推荐阅读