【问题标题】:Parse local webpages with Selenium in VBA Excel fails在 VBA Excel 中使用 Selenium 解析本地网页失败
【发布时间】:2016-01-08 19:46:58
【问题描述】:

我想解析本地保存的网页列表。遗憾的是网页无法使用 Internet Explorer 打开(错误是“页面没有响应”),但 FireFox 可以正常打开它们。所以我必须找到一个“解决方法”来获取源代码,以便我可以解析它以获得我想要的信息。因此我找到了 SeleniumBasic。
我使用 Excel 2013 和 SeleniumBasic 2.0.6.0

使用 Selenium 时遇到以下问题。这是代码应该是的非常简短的版本:

Sub TestSeleniumParsing()

    Dim sel As Selenium.WebDriver
    Set sel = New Selenium.WebDriver
    Dim html As HTMLDocument
    Dim ihtml As IHTMLElement
    Dim ihtmlcoll As IHTMLElementCollection

    sel.Start "firefox", "about:blank"
    sel.Get "file:///D:/LocalWebPages/MV_999.htm" 'GET LOCAL WEBPAGE

    Set html = New HTMLDocument
    html.body.innerHTML = sel.PageSource
    Set sel = Nothing

    Set ihtmlcoll = html.getElementsByClassName("name") ' THIS IS THE LINE WITH THE ERROR 
                                                    WHICH USED TO WORK WHEN I USED 
                                                    InterExporerMedium INSTEAD OF Selenium
    For Each ihtml In ihtmlcoll
        'SOME CODE HERE BUT NOW NOT IMPORTANT...
    Next ihtml


    Set html = Nothing
    Set ihtml = Nothing
    Set ihtml = Nothing

End Sub

Set ihtmlcoll = html.getElementsByClassName("name") 行,我收到一个错误,之前我在使用 Internet Explorer 时没有收到:

我不想在 Selenium VBA 中编写所有内容的原因是因为我已经在 VBA 中编写了代码。

任何帮助深表感谢。

PS:这个问题和这个here有关。

【问题讨论】:

    标签: html vba excel parsing selenium


    【解决方案1】:

    使用 SeleniumBasic 获取 DOM 的正确方法:

    Sub Get_DOM_Late_Binding()
      Dim driver As New FirefoxDriver
      driver.Get "https://en.wikipedia.org/wiki/Main_Page"
    
      Dim html: Set html = CreateObject("htmlfile")
      html.Write driver.PageSource()
    
      Debug.Print html.body.innerText      
      driver.Quit
    End Sub
    
    Sub Get_DOM_Early_Binding()
      Dim driver As New FirefoxDriver
      driver.Get "https://en.wikipedia.org/wiki/Main_Page"
    
      Dim html As New HTMLDocument  ' Requires Microsoft HTML Library
      html.body.innerHTML = driver.ExecuteScript("return document.body.innerHTML;")
      ' CallByName html, "Write", VbMethod, driver.PageSource()
    
      Debug.Print html.body.innerText      
      driver.Quit
    End Sub
    

    要使用上述示例获取最新版本: https://github.com/florentbr/SeleniumBasic/releases/latest

    【讨论】:

    • Florent B. 你真是个天才。我很幸运能遇到你的解决方案。看到这个答案没有被接受,我吓了一跳。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2021-11-28
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    相关资源
    最近更新 更多