【发布时间】:2015-04-09 17:34:08
【问题描述】:
目前,我正在从 data.cnbc.com/quotes/sdrl 解析报价表,并将 innerhtml 放入我指定的代码旁边的列中。
所以,我会从 A2 中获取符号,然后将产量数据放入 C2,然后移动到下一个符号。
HTML 看起来像:
<table id="fundamentalsTableOne">
<tbody>
<tr scope="row">
<th scope="row">EPS</th>
<td>8.06</td>
</tr>
<tr scope="row">
<th scope="row">Market Cap</th>
<td>5.3B</td>
</tr>
<tr scope="row">
<th scope="row">Shares Out</th>
<td>492.8M</td>
</tr>
<tr scope="row">
<th scope="row">Price/Earnings</th>
<td>1.3x</td>
</tr>
</tbody>
</table>
<table id="fundamentalsTableTwo">
<tbody>
<tr scope="row">
<th scope="row">Revenue (TTM)</th>
<td>5.0B</td>
</tr>
<tr scope="row">
<th scope="row">Beta</th>
<td>1.84</td>
</tr>
<tr scope="row">
<th scope="row">Dividend</th>
<td>--</td>
</tr>
<tr scope="row">
<th scope="row">Yield</th>
<td><span class="pos">0.00%</span></td>
</tr>
</tbody>
</table>
目前,我有:
Sub getInfoWeb()
Dim cell As Integer
Dim xhr As MSXML2.XMLHTTP60
Dim doc As MSHTML.HTMLDocument
Dim table As MSHTML.HTMLTable
Dim tableCells As MSHTML.IHTMLElementCollection
Set xhr = New MSXML2.XMLHTTP60
For cell = 2 To 5
ticker = Cells(cell, 1).Value
With xhr
.Open "GET", "http://data.cnbc.com/quotes/" & ticker, False
.send
If .readyState = 4 And .Status = 200 Then
Set doc = New MSHTML.HTMLDocument
doc.body.innerHTML = .responseText
Else
MsgBox "Error" & vbNewLine & "Ready state: " & .readyState & _
vbNewLine & "HTTP request status: " & .Status
End If
End With
Set table = doc.getElementById("fundamentalsTableOne")
Set tableCells = table.getElementsByTagName("td")
For Each tableCell In tableCells
Cells(cell, 2).Value = tableCell.NextSibling.innerHTML
Next tableCell
Next cell
End Sub
但是,我收到“拒绝访问”错误,并且在我的 set tablecells 行中出现运行时 91。这是因为每一行中只有一个元素,并且 tablecells 被设置为一个集合吗?此外,是否由于从 javascript 生成的 HTML 导致“访问被拒绝”错误?我不认为这应该是个问题。
如果有人知道如何使它工作,将不胜感激。谢谢。
【问题讨论】:
-
如果内容是在客户端动态生成的,那么您的方法将不起作用,您需要改为(例如)自动化 IE 以加载页面并从中读取内容在那里。
-
谢谢,蒂姆。我将修改并尝试浏览器路由。
标签: html vba parsing excel web-scraping