当我在搜索框中插入少量单词时,它会提取相关数据。 我需要从中选择第一个选项。
有一个网站“ https://indiarailinfo.com/” 当我从电台框中搜索“ ADI”时,系统正在提取名称中带有“ ADI”的相关电台?第一个选项总是显示与它非常接近的匹配。 如何使用VBA代码从中选择“首选”
Dim ie As Object
Set ie = CreateObject("InternetExplorer.Application")
ie.navigate "https://indiarailinfo.com/"
While ie.readyState <> 4: DoEvents: Wend
ie.Visible = True
ie.document.querySelector("[placeholder='from station']").Value = "ADI"
可以从该站点获得HTML代码
它在下拉菜单中首当其冲,例如“ ADI /艾哈迈达巴德交界处” 我怎样才能在选定的答案中得到这个答案?
亲切建议
答案 0 :(得分:1)
自动化纯粹主义者不喜欢使用javascript来执行,但我将在这里使用IE触发下拉菜单。如果我要走纯净路线,我会使用硒。
Option Explicit
Public Sub MakeSelection()
Dim ie As InternetExplorer, t As Date, dropdown1 As Object
Set ie = New InternetExplorer
Const MAX_WAIT_SEC As Long = 5
With ie
.Visible = True
.Navigate2 "https://indiarailinfo.com/"
While .Busy Or .readyState < 4: DoEvents: Wend
With .document.querySelector("[placeholder='from station']")
.Focus
.Value = "ADI"
ie.document.parentWindow.execScript "document.querySelector('[placeholder^=from]').click();"
End With
t = Timer
Do
DoEvents
On Error Resume Next
Set dropdown1 = .document.querySelectorAll(".icol span")
On Error GoTo 0
If Timer - t > MAX_WAIT_SEC Then Exit Do
Loop While dropdown1.Length = 0
If dropdown1.Length > 0 Then
dropdown1.item(0).Click
End If
Stop
.Quit
End With
End Sub
对于使用Selenium basic的自动化纯粹主义者
Option Explicit
Public Sub MakeSelection()
Dim d As WebDriver
Set d = New ChromeDriver
Const Url = "https://indiarailinfo.com/"
With d
.Start "Chrome"
.get Url
.FindElementByCss("[placeholder='from station']").SendKeys "ADI"
.FindElementByCss(".icol span").Click
Stop
.Quit
End With
End Sub