Selenium Web Scraping:如何与Select2下拉选择框交互?
解决Selenium操作Select2隐藏下拉框的问题
问题详情
使用Selenium进行网页抓取时,无法与Select2下拉选择框交互:
- 原生
<select>元素(id为Lbl1)被标记为select2-hidden-accessible,处于隐藏状态 - 直接定位该元素执行
SendKeys "1000-111"无响应 - 执行Click操作时抛出错误:
Run-Time error 11 Element NotVisibleError element not interactable
组件HTML结构
点击前
<div class="form-group"> <label class="control-label required" for="Lbl1"> Text Bla bla bla </label> <select id="Lbl1" name="Lbl2[Lbl3]" class="form-control select2-hidden-accessible" tabindex="-1" aria-hidden="true"></select> <span class="select2 select2-container select2-container--default select2-container--focus" dir="ltr" style="width: 274.484px;"> <span class="selection"> <span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-labelledby="select2-Lbl1-container"> <span class="select2-selection__rendered" id="select2-Lbl1-container" title="null"></span> <span class="select2-selection__arrow" role="presentation"> <b role="presentation"></b> </span> </span> </span> <span class="dropdown-wrapper" aria-hidden="true"></span> </span> </div>
点击后
<span class="select2 select2-container select2-container--default select2-container--below select2-container--open" dir="ltr" style="width: 274.484px;"> <span class="selection"> <span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="true" tabindex="0" aria-labelledby="select2-Lbl1-container" aria-owns="select2-Lbl1-results"> <span class="select2-selection__rendered" id="select2-Lbl1-container" title="null"></span> <span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span> </span> </span> <span class="dropdown-wrapper" aria-hidden="true"></span> </span>
用户原VBA代码
Dim comboBox As Object Set comboBox = gc.FindElementById("Lbl1") comboBox.SendKeys "1000-111"
解决方案
Select2会隐藏原生<select>,必须操作其渲染后的可视化DOM元素,步骤如下:
- 定位Select2的触发容器(带
select2-selection--single类的span),点击打开下拉框 - 定位下拉框内的搜索输入框(
select2-search__field类),输入目标值 - 选择匹配的结果项
修改后的VBA代码
Dim select2Trigger As Object Dim searchInput As Object Dim resultItem As Object ' 定位Select2触发按钮并点击打开下拉框 Set select2Trigger = gc.FindElementByCss(".select2-selection--single") select2Trigger.Click ' 等待下拉框加载,定位搜索输入框并输入目标值 gc.Wait 2000 Set searchInput = gc.FindElementByCss(".select2-search__field") searchInput.SendKeys "1000-111" ' 等待结果加载,选择匹配的选项 gc.Wait 1000 Set resultItem = gc.FindElementByCss(".select2-results__option[aria-selected='false']") resultItem.Click
补充说明
- 若页面加载较慢,建议用显式等待替代固定等待时间,示例:
Set wait = New WebDriverWait wait.Timeout = 10 Set select2Trigger = wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector, ".select2-selection--single")) - 若目标选项无需搜索直接存在,可跳过搜索步骤,直接定位对应选项点击
内容的提问来源于stack exchange,提问作者Astos
相关产品推荐
相关产品推荐

