[英]Pull value from website (HTML div class) using Excel VBA
I'm trying to automate going to a website and pulling the ratings from several apps.我正在尝试自动访问网站并从多个应用程序中提取评级。
I've figured out how to navigate and login to the page.我已经找到了如何导航和登录页面的方法。
How do I pull the element - the number "3.3" in this case - from this specific section into Excel.我如何将元素(在本例中为数字“3.3”)从该特定部分拉入 Excel。
Being unfamiliar with HTML in VBA, I got this far following tutorials/other questions.由于不熟悉 VBA 中的 HTML,我在教程/其他问题之后得到了这么远。
Rating on website and the code behind it网站评级及其背后的代码
Sub PullRating()
Dim HTMLDoc As HTMLDocument
Dim ie As InternetExplorer
Dim oHTML_Element As IHTMLElement
Dim sURL As String
On Error GoTo Err_Clear
sURL = "https://www.appannie.com/account/login/xxxxxxxxxx"
Set ie = New InternetExplorer
ie.Silent = True
ie.navigate sURL
ie.Visible = True
Do
'Wait until the Browser is loaded
Loop Until ie.readyState = READYSTATE_COMPLETE
Set HTMLDoc = ie.Document
HTMLDoc.all.Email.Value = "xxxxxxxxx@xxx.com"
HTMLDoc.all.Password.Value = "xxxxx"
For Each oHTML_Element In HTMLDoc.getElementById("login-form")
If oHTML_Element.Type = "submit" Then oHTML_Element.Click: Exit For
Next
Dim rating As Variant
Set rating = HTMLDoc.getElementsByClassName("rating-number ng-binding")
Range("A1").Value = rating
'ie.Refresh 'Refresh if required
Err_Clear:
If Err <> 0 Then
Err.Clear
Resume Next
End If
End Sub
The code below will let you extract text from first element with class name "rating-number ng-binding" in HTML document.下面的代码将让您从 HTML 文档中类名为“rating-number ng-binding”的第一个元素中提取文本。 By the way GetElementsByClassName is supported since IE 9.0.
顺便说一下,从 IE 9.0 开始支持 GetElementsByClassName。 I use coding compatible also with older versions in my example.
在我的示例中,我使用的编码也与旧版本兼容。
Dim htmlEle1 as IHTMLElement
For Each htmlEle1 in HTMLDoc.getElementsByTagName("div")
If htmlEle1.className = "rating-number ng-binding" then
Range("A1").Value = htmlEle1.InnerText
Exit For
End if
Next htmlEle1
While Ryszards code should do the trick if you want to use the code you have already written then here is the alterations I believe you need to make.如果您想使用已经编写的代码,Ryszards 代码应该可以解决问题,但这里是我认为您需要进行的更改。
For Each oHTML_Element In HTMLDoc.getElementById("login-form")
If oHTML_Element.Type = "submit" Then oHTML_Element.Click: Exit For
Next
'Need to wait for page to load before collecting the value
Loop Until ie.readyState = READYSTATE_COMPLETE
Dim rating As IHTMLElement
Set rating = HTMLDoc.getElementsByClassName("rating-number ng-binding")
'Need to get the innerhtml of the element
Range("A1").Value = rating.innerhtml
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.