Syntax Error Issue on VBA

2019-07-25 22:12发布

I am trying to extract some values using VBA from a Website

The following code contains the array of the data I am looking for. This works perfectly and gives me the array of the data I am looking for.

document.getElementsByClassName("list-flights")(0).querySelectorAll("[class$='price']")

The result for the above is

<NodeList length="23">...</NodeList>

But when I am trying to extract the values by running the loop in a VBA by using the following code

lnth = document.getElementsByClassName("list-flights")(0).querySelectorAll("[class$='price']").Length - 1

For x = 0 To lnth

    firstResult = document.getElementsByClassName("list-flights")(0).querySelectorAll("[class$='price']")(x).innerText

Next x

The code would give error at firstResult since it would not get any value. I checked on Internet Explorer there is no value if I use "(" brackets,however if I use "[" on Internet Explorer it works but VBA would not accept "[" Brackets.

document.getElementsByClassName("list-flights")(0).querySelectorAll("[class$='price']")[0] 

The code above works on Internet Explorer Console but cant be used in VBA.

I am sure I am missing something would be of great help if you can advice what is the workaround on this.

enter image description here

1条回答
ゆ 、 Hurt°
2楼-- · 2019-07-25 23:00

To get the innerText, you can use getElementsByClassName 2 more times, one of them inside for each .. next loop since your values are in list-flights -> price -> cash js_linkInsideCell:

Set priceData = IE.document.getElementsByClassName("list-flights")(0).getElementsByClassName("price")

For Each Item In priceData
    Debug.Print Item.getElementsByClassName("cash js_linkInsideCell")(0).innerHTML
Next Item

Using .querySelectorAll("[class$='price']") works as well, but it crashes IE object after parsing. Try and see if it crashes:

Set priceData = IE.document.getElementsByClassName("list-flights")(0).querySelectorAll("[class$='price']")

For Each Item In priceData
    Debug.Print Item.getElementsByClassName("cash js_linkInsideCell")(0).innerHTML
Next Item

Some quick notes:

1-You can use this code to wait for IE object to load url:

Do While IE.Busy
    DoEvents
Loop

2-Sometimes, even if IE object is ready, query results are not returned that fast. This means the elements you are looking for are not ready yet and do not exists so you get an error message:

Run-time error '91': Object variable or With block variable not set

To avoid this message my workaround is as follows:

Do
On Error Resume Next
Set priceData = IE.document.getElementsByClassName("list-flights")(0).getElementsByClassName("price")
Loop Until Err.Number <> 91

I hope this helps.

查看更多
登录 后发表回答