首页 文章

如何使用Excel / VBA按元素ID从外部网站提取值?

提问于
浏览
0

我正在尝试使用VBA按元素ID从外部网站检索值,并将它们添加到我的excel表中 . 网站URL显示在A列中.B列和C列用于检索到的值 .

URL example元素ID名称:"youtube-user-page-country"

Excel Pic

贝娄是我糟糕的尝试:

Sub getCountry()

 Dim IE As New InternetExplorer
 IE.Visible = False

 IE.navigate Worksheets("Sheet1").Range(A3).Value
 Do
 DoEvents
 Loop Until IE.readyState = READYSTATE_COMPLETE

 Dim Doc As HTMLDocument
 Set Doc = IE.document

Dim getCountry As String

getCountry = Trim(Doc.getElementsByTagName("youtube-user-page-country").innerText)

Worksheets("Sheet1").Range(B31).Value = getCountry

End Sub

代码无法显示对象定义问题 . 谁能给我一些关于我哪里出错的提示?

我一直是宏 Logger 的用户,而且开关的学习曲线非常陡峭:-)

谢谢你的帮助 !

2 回答

  • 1

    我想我得到了你想要的东西 . 有一些问题:

    • 您想使用 getElementByID .

    • 命名一个字符串 getCountry ,包含它的SubRoutine getCountry 不是一个好主意 . 你可以做到,但不要 .

    • 始终完全限定您的工作表参考,以便您了解正在使用的工作簿和工作表

    这是经过修改的代码,我的工作就在我的最后 .

    Sub getCountry()
        Dim IE      As Object: Set IE = CreateObject("InternetExplorer.Application")
        Dim ws      As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
        Dim Country As String
    
        With IE
            .Visible = False
            .navigate ws.Range("A3").Value
    
            Do
                DoEvents
            Loop Until .readyState = 4
    
        End With
    
        Country = Trim$(IE.document.getElementByID("youtube-user-page-country").innerText)
        ws.Range("B31").Value2 = Country
        IE.Quit
    End Sub
    
  • 0

    您可以使用它将数据转储到电子表格中 .

    Sub DumpData()
    
    Set IE = CreateObject("InternetExplorer.Application")
    IE.Visible = True
    
    URL = "http://finance.yahoo.com/q?s=sbux&ql=1"
    
    'Wait for site to fully load
    IE.Navigate2 URL
    Do While IE.Busy = True
       DoEvents
    Loop
    
    RowCount = 1
    
    With Sheets("Sheet1")
       .Cells.ClearContents
       RowCount = 1
       For Each itm In IE.document.all
          .Range("A" & RowCount) = itm.tagname
          .Range("B" & RowCount) = itm.ID
          .Range("C" & RowCount) = itm.classname
          .Range("D" & RowCount) = Left(itm.innertext, 1024)
    
          RowCount = RowCount + 1
       Next itm
    End With
    End Sub
    

    谢谢乔尔!

相关问题