【问题标题】:How to web scrape Twitter with VBA using Chrome browser?如何使用 Chrome 浏览器通过 VBA 抓取 Twitter?
【发布时间】:2020-06-22 11:24:51
【问题描述】:

我正在尝试使用 VBA 抓取 Twitter。该代码在其他使用 Internet Explorer 的网站上运行良好,但由于 Internet Explorer 无法打开 Twitter 网站,我正在尝试用 Chrome 浏览器替换它。我找到了如何在 Chrome 中打开 URL,但不知道应该放什么来从 HTML 文档中检索数据。下面,我保留了适用于 Internet Explorer 的代码,并添加了打开 Chrome 浏览器的代码。我的主要问题是我应该放什么而不是“?????????”在以下代码中:

Sub GetData()
    
    Dim objIE As InternetExplorer
    Dim itemEle As Object
    Dim desc As String, a As String, title As String, titleDate As String
    
    Dim y As Integer
    Dim sURL As String
    Dim lastrow As Long
 
    Dim chromePath As String
    
    chromePath = """C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"""
    
    lastrow = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row
    y = 2
    
    For i = 2 To lastrow
    
  
    sURL = Sheet1.Cells(i, 1)
    'Set objIE = New InternetExplorerMedium
    'objIE.Visible = True
 
    Shell (chromePath & Sheets("profileLinks").Cells(i, 1))
 
    'objIE.navigate sURL
    'Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop
    
    On Error GoTo err_clear
    Application.Wait (Now + TimeValue("0:00:10"))
    
    
    For Each itemEle In ?????????.document.getElementsByClassName("css-901oao css-bfa6kz r-111h2gw r-18u37iz r-1qd0xha r-a023e6 r-16dba41 r-ad9z0x r-bcqeeo r-qvutc0")
        Text = itemEle.getElementsByTagName("span")(0).innerText
    
        Sheets("Outcome").Range("A" & y).Value = Text

        y = y + 1
    Next
    
    'objIE.Quit
    Next i
    
err_clear:
        If Err <> 0 Then
        Err.Clear
        Resume Next
        End If
    
End Sub

请随时提出任何其他解决方案。提前谢谢你。

【问题讨论】:

    标签: vba web-scraping


    【解决方案1】:

    我认为您需要额外的对象变量来保存对 html 对象库中对象的引用。例如,在引用 Microsoft HTML Object library 之后,您可以像这样添加:

    Dim HTMLDocument As MSHTML.HTMLDocument
    Dim itemEle As MSHTML.IHTMLElement
    Dim itemCollection AS MSHTML.IHTMLElementCollection
    
    Set HTMLDocument = objIE.Document
    Set itemCollection = HTMLDocument.getElementsByClassName("...")
    
    For Each itemEle in itemCollection
    'extra code here
    Next itemEle
    

    我希望这能回答你的问题!

    【讨论】:

      猜你喜欢
      • 2019-09-05
      • 2021-03-20
      • 2019-11-29
      • 1970-01-01
      • 2012-11-03
      • 1970-01-01
      • 1970-01-01
      • 2019-07-02
      • 2016-02-09
      相关资源
      最近更新 更多