Как перенести данные с сайта Inte rnet Explorer в Excel? Получить элемент по идентификатору (нг-контент) - PullRequest
0 голосов
/ 20 января 2020

Я разрабатываю макрос в Excel (VBA) для загрузки информации из электронной таблицы Excel в Inte rnet Explorer (URL: https://www.tarifasdepedagios.com.br/tarifas/inicial), чтобы нажать кнопку вычисления и, после, получить результаты из IE в электронную таблицу Excel.

Как перенести данные результатов из Inte rnet Explorer в Excel?

Пример:

Входные данные:

  • Происхождение: Сан-Паулу, SP, Бразилия
  • Назначение: Рио-де-Жанейро, RJ, Бразилия

Результаты:

  • Расстояние: 435,06 км (ID в HTML коде: "mat-input-3")
  • Стоимость звонка: R $ 59,70 (ID в HTML code: "mat-input-5")

Можно ли получить эти результаты на getElementsbyID в VBA?

Ошибка связана с "ng-content" в HTML код?

Ссылка HTML Код: https://i.stack.imgur.com/AWoEW.png

Код VBA указан ниже:

Sub Pesquisa_Informações_Rota_TarifasdePedagios()

  Dim IE As InternetExplorer, CidadeOrig As String, sng As Date
  Dim LR As Long, Contador As Long, CidadeDest As String

  Dim RS_litro As String
  Dim km_litro As String
  Dim Percentual As Single

  'Limpa os resultados da última pesquisa realizada

  Sheets("tarifasdepedagios.com.br").Select
  Range("C5:F5").Select
  Range(Selection, Selection.End(xlDown)).Select
  Selection.ClearContents
  Range("A1").Select

  'Identifica a última célula ativa da lista
  Sheets("tarifasdepedagios.com.br").Select
  LR = Cells(Rows.Count, 1).End(xlUp).Row

  'Cria um objeto Internet Explorer
  Set IE = New InternetExplorer

  'Torna o objeto visível
  IE.Visible = True 'True ou False

  'Faz um loop por todas as linhas da planilha
   For Contador = 5 To LR

     'Navega ao site do Tarifas de Pedagios
     IE.Navigate "https://www.tarifasdepedagios.com.br/tarifas/inicial"

    'Identifica se a página já foi totalmente carregada
     While IE.readyState <> READYSTATE_COMPLETE
     Wend
     sng = Timer
     Do While sng + 3 > Timer
     Loop

     'Carrega os dados de cidade de origem e destino que serão preenchidos na página
     RS_litro = Range("B1").Value
     km_litro = Range("B2").Value
     CidadeOrig = Range("A" & Contador).Value
     CidadeDest = Range("B" & Contador).Value

     'Carrega os dados de cidade de origem e destino na página e submente os dados do formulário
     IE.document.all.Item("mat-input-9").Click
     IE.document.all("mat-input-9").Value = CidadeOrig
     IE.document.all.Item("mat-input-10").Click
     IE.document.all("mat-input-10").Value = CidadeDest
     IE.document.all("mat-input-0").Value = RS_litro
     IE.document.all("mat-input-1").Value = km_litro
     IE.document.all.Item("botaoRoteirizar").Click

    'Identifica se a página já foi totalmente carregada
     While IE.readyState <> READYSTATE_COMPLETE
     Wend
     sng = Timer
     Do While sng + 3 > Timer
     Loop

    'Retorna os valores de distância, tempo, pedágio e combustível nas colunas 'C', 'D', 'E' e 'F'
    Cells(Contador, 3) = IE.document.getElementsById("mat-input-3")(0).Value <- ERROR HERE (Run-time error '438' Object doesn't support this property or method)
    Cells(Contador, 4) = IE.document.getElementsById("mat-input-4")(0).Value
    Cells(Contador, 5) = IE.document.getElementsById("mat-input-6")(0).Value
    Cells(Contador, 6) = IE.document.getElementsById("mat-input-5")(0).Value

    Percentual = (Contador - 4) / (LR - 4)

    AtualizaBarra Percentual

    Next Contador

    IE.Quit

    frmProcesso.Hide

    MsgBox "Olá, " & Application.UserName & "!" + vbCrLf + "Pesquisa finalizada!"

End Sub

1 Ответ

0 голосов
/ 21 января 2020

Функция должна быть getElementById вместо getElementsById. Он получает определенный элемент в HTML, и вы можете обратиться к этой ссылке для использования.

Вы должны изменить свой код следующим образом из строки ошибки:

'Retorna os valores de distancia, tempo, pedágio e combustível nas colunas 'C', 'D', 'E' e 'F'
    Cells(Contador, 3) = IE.document.getElementById("mat-input-3").Value
    Cells(Contador, 4) = IE.document.getElementById("mat-input-4").Value
    Cells(Contador, 5) = IE.document.getElementById("mat-input-6").Value
    Cells(Contador, 6) = IE.document.getElementById("mat-input-5").Value
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...