excel - 使用 Classname 从网站将数据复制到使用 VBA 的 Excel
问题描述
我正在尝试从网站获取信息,但无法获取任何数据。 https://markets.cboe.com/us/equities/market_statistics/book/AAPL/ 我在这篇文章中遇到了同样的问题R rvest retrieve empty table 如何在 VBA 中做到这一点?我在互联网上找到了这段代码,我对其进行了修改,但它没有获取数据,并且信息显示在一个窗口中,而不是粘贴到电子表格中。如果您直接导出整个表格,那就太好了,否则我将不得不逐个单元格地复制。提前致谢!
Sub Get_Web_Data()
Dim request As Object
Dim response As String
Dim html As New HTMLDocument
Dim website As String
Dim price As Variant
' Website to go to.
website = "https://markets.cboe.com/us/equities/market_statistics/book/AAPL/"
' Create the object that will make the webpage request.
Set request = CreateObject("MSXML2.XMLHTTP")
' Where to go and how to go there - probably don't need to change this.
request.Open "GET", website, False
' Get fresh data.
request.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
' Send the request for the webpage.
request.send
' Get the webpage response data into a variable.
response = StrConv(request.responseBody, vbUnicode)
' Put the webpage into an html object to make data references easier.
html.body.innerHTML = response
' Get the price from the specified element on the page.
price = html.getElementsByClassName("book-viewer__ask book-viewer__ask-shares").Item(2).innerText
' Output the price into a message box.
MsgBox price
End Sub
解决方案
而是使用 Internet Explorer 并在 vba 中打开 Microsoft Internet 控件,我使用此代码并设法从同一网站提取数据并粘贴到单元格中;
子互联网()
Dim IEe As InternetExplorer
Dim doc, element
Set IEe = New InternetExplorer
IEe.Visible = TRUE
IEe.Navigate "https://markets.cboe.com/us/equities/market_statistics/book/AAPL/"
Do While IEe.ReadyState = 4: DoEvents: Loop
Do Until IEe.ReadyState = 4: DoEvents: Loop
Set element = IEe.Document.getElementByID("id="ext-gen1057"") 'to get the ID, right click in internet explorer and pick the inspect element option the click on the data you want
thisworkbook.sheets("sheet1").range("a1")= element.value
end sub
推荐阅读
- java - 如何使用给定的变量设置while循环以保持重复单词并将它们添加到数组列表中
- sql - oracle sql - 在 with 语句中将日期定义为变量
- json - 使用包含不同类型字典的 Swift 解码 JSON
- java - 在 Java 和 C++ 之间传递数据
- arrays - firebase 使用数组将数据添加到数据库
- c# - 在结构性能影响中包装 C# 原语
- python - 这些 Big-O 符号对于简单的模数和幂函数 (Python) 是否正确?
- swiftui - SwiftUI 使文本部分可点击
- python - 如何限制自定义验证器仅将错误推送到 field.errors 而不是 django 消息?
- c# - ef form app c# code first with sqlite error db.SaveChanges no such a table