getElementsBy() extract text

非 Y 不嫁゛ 提交于 2019-12-25 01:30:03

问题


I'm really new to VBA and I've been trying to get the value below the Column "Impuesto".

I'm getting error 438. I still don't quite understand how to refer to a certain part of the web page.

Sub extract()

Dim myIE As Object
Dim myIEDoc As Object
Dim element As IHTMLElement

Set myIE = CreateObject("InternetExplorer.Application")

myIE.Visible = False

myIE.navigate "https://zonasegura1.bn.com.pe/TipoCambio/"

While myIE.Busy
    DoEvents
Wend
 Set myIEDoc = myIE.document


Range("B1") = myIEDoc.getElementsByID("movimiento")(0).getElementsByTagName("span")

End Sub

回答1:


Try the below script. It should fetch you the data you are after. When the execution is done, you should find the value in Range("A1") in your spreadsheet.

Sub Get_Quote()
    Dim post As Object

    With CreateObject("InternetExplorer.Application")
        .Visible = True
        .navigate "https://zonasegura1.bn.com.pe/TipoCambio/"
        While .Busy = True Or .readyState < 4: DoEvents: Wend
        Set post = .document.querySelector(".movimiento span.l2.valor")
        [A1] = post.innerText
        .Quit
    End With
End Sub



回答2:


You need getElementsByClassName() not getElementsByID since the word movimiento is in <li class="movimiento bg"> Impuesto </li>

Range("B1") = myIEDoc.getElementsByClassName("movimiento")(0).getElementsByClassName("l2 valor")(0)

Edit:

Check out the tag if the tag name if <li>..</li> so you should getElementsByTagName("li")

Check out the tag if the tag contain id <li id="movimiento">..</li> so you should getElementByID("movimiento")

Check out the tag if the tag contain class <li class="movimiento">..</li> so you should getElementsByClassName("movimiento")




回答3:


It is faster to use XMLHTTP request as follows:

Option Explicit
Public Sub GetInfo()
    Dim sResponse As String, html As HTMLDocument
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://zonasegura1.bn.com.pe/TipoCambio/", False
        .setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
        .send
        sResponse = StrConv(.responseBody, vbUnicode)
    End With
    Set html = New HTMLDocument
    With html
        .body.innerHTML = sResponse
        Debug.Print .querySelector(".movimiento .l2.valor").innerText
    End With
End Sub


来源:https://stackoverflow.com/questions/48858435/getelementsby-extract-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!