我正在尝试从网站中提取数据。所以我想在下面的URL中选择3个下拉值,但是我无法更改这些值。例如,我想选择月份
<select name="fmonth1" id="fmonth1" class="dropdownboxlang" size="1" style="width:60px;">
<option value="0">MM</option>
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
<option value="4">Apr</option>
<option value="5">May</option>
<option value="6">Jun</option>
<option value="7">Jul</option>
<option value="8">Aug</option>
<option value="9">Sep</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
更改下拉列表中的值时出现的错误。我从两天开始尝试所有可能的方法。任何建议,将不胜感激。
Public Sub bse()
Dim IE As InternetExplorer
Dim HTML As HTMLDocument
Dim Dropdown As IHTMLElement
Dim dropOption As IHTMLElement
Set IE = CreateObject("InternetExplorer.Application")
With IE
.Visible = True
.Navigate "https://www.bseindia.com/markets/debt/BhavCopyDebt.aspx?expandable=6"
End With
Do
DoEvents
Application.Wait Now() + TimeValue("00:00:01")
Loop Until IE.ReadyState = 4 And Not IE.Busy
Set HTML = IE.Document
HTML.getElementsByName("fmonth1")(0).Value = "1" error line
IE.Quit
End Sub
答案 0 :(得分:1)
您可以将css id选择器与属性=值选择器一起使用
#fmonth1 option[value='1']
也就是说:
ie.document.querySelector("#fmonth1 option[value='1']")
您可能需要。单击末尾以进行选择。无法测试该网址,但也可以尝试:
ie.document.querySelector("#fmonth1 option[value='1']").Selected = True
更一般而言,如果您知道某个元素存在,并且语法正确,但是仍未设置,则可能是计时问题,您需要更长的等待时间(例如定时循环)才能尝试访问,例如
Const MAX_WAIT_SEC As Long = 10
Dim t As Date, ele As Object
t = Timer
Do
DoEvents
On Error Resume Next
Set ele = ie.document.querySelector("#fmonth1")
On Error GoTo 0
If Timer - t > MAX_WAIT_SEC Then Exit Do
Loop While ele Is Nothing
If Not ele Is Nothing Then
ele.Click 'may be needed to expose options
ie.document.querySelector("#fmonth1 option[value='1']").Selected = True
End If
如果在父iframe /框架内部,则需要先导航到该位置
ie.document.getElementsByTagName("iframe")(0).contentDocument.querySelector("#fmonth1 option[value='1']").Selected = True
我已经测试了以下内容,现在可以访问该页面:
Public Sub MakeSelection()
Dim ie As New InternetExplorer
With ie
.Visible = True
.navigate "https://www.bseindia.com/markets/debt/BhavCopyDebt.aspx?expandable=6"
While .Busy Or .readyState < 4: DoEvents: Wend
.document.getElementsByTagName("iframe")(0).contentDocument.querySelector("#fmonth1 option[value='1']").Selected = True
Stop '<==Delete me later
.Quit
End With
End Sub