我希望使用VBA代码将网页上的表格中的数据复制到Excel中,但在Excel工作表上什么也没得到:(。
我试图将来自不同来源的一些VBA代码放在一起。这是我的代码:
Sub CopyWebData()
Dim IE As Object
On Error Resume Next
Application.DisplayAlerts = False
Set IE = CreateObject("InternetExplorer.Application")
With IE
.Visible = True
.navigate "https://eresearch.fidelity.com/eresearch/evaluate/fundamentals/earnings.jhtml?tab=details&symbols=GOOG"
Do Until .readyState = 4: DoEvents: Loop
End With
Dim idoc As MSHTML.HTMLDocument
Dim elem As MSHTML.IHTMLElement
Set idoc = IE.document
Set elem = idoc.getElementsByClassName("layout-outer-table-width")(0).innerText
Sheets("Sheet1").Activate
Range("A1:A1000") = "" ' erase previous data
Range("A1").Select
Range("A1").Value = elem
End Sub
这是一个受密码保护的网页,我已经登录,因此可以看到该网页已被VBA代码成功撤出。但是,此网页上的表中的数据未能复制到excel中-在目标工作表上看不到任何内容。
如您所见,我使用代码.getElementsByClassName(“ layout-outer-table-width”),因为我使用了Chrome的“检查”功能来检查网页,并发现鼠标悬停在语句上方时:>
...<table cellspacing="0" cellpadding="0" border="0" class="layout-outer-table-width"> == $0
<tbody>...</tbody>
</table>
覆盖我所需表格的网页的部分已加阴影。然后,我在类名“ layout-outer-table-width”中编码。但是,正如我所说,我在Excel工作表上没有看到任何内容。
任何指导将不胜感激!
答案 0 :(得分:0)
如果在收入明细表之后,您需要其他选择器。我正在显示该表的CSS选择器。您当前的选择器(类)和索引0在面包屑(导航树)上匹配。该类也不适合选择页面上的表格。
.earningsHistoryTable-Cont table
我无法对此进行测试,但您可能还希望表存在一个定时循环
Option Explicit
'VBE > Tools > References:
' Microsoft Internet Controls
Public Sub RetrieveInfo()
Dim IE As InternetExplorer, hTable As Object, clipboard As Object, t As Date
Const MAX_WAIT_SEC As Long = 5
Set clipboard = GetObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
Set IE = New InternetExplorer
With IE
.Visible = True
.Navigate2 "https://eresearch.fidelity.com/eresearch/evaluate/fundamentals/earnings.jhtml?tab=details&symbols=GOOG"
While .Busy Or .readyState < 4: DoEvents: Wend
With .document
.querySelector("#userId").Value = "xyz"
.querySelector("#password").Value = "123456"
.querySelector("form").submit
End With
While .Busy Or .readyState < 4: DoEvents: Wend
t = Timer 'timed loop for details table to be present
Do
On Error Resume Next
Set hTable = IE.document.querySelector(".earningsHistoryTable-Cont table")
On Error GoTo 0
If Timer - t > MAX_WAIT_SEC Then Exit Do
Loop While hTable Is Nothing
If Not hTable Is Nothing Then 'use clipboard to copy paste
clipboard.SetText hTable.outerHTML
clipboard.PutInClipboard
ThisWorkbook.Worksheets("Sheet1").Range("A1").PasteSpecial
End If
End With
End Sub