如何获取点击后元素未变更的下拉框选中值?
解决自定义下拉框选中值获取问题
问题场景
用Selenium Firefox打开SoccerWay上伊图阿诺俱乐部的统计页面后,页面内有个赛事选择下拉框,HTML结构如下:
<table class="table compare section-dropdowns"> <thead> <tr class="sub-head dropdown-head"> <th class="col1"> </th> <th><div data-active-dropdown-id="" class="active-dropdown"> <select name="competition_id"> <option value="89" selected="selected">Serie B - 2023</option> <option value="239">Paulista A1 - 2023</option> <option value="231">Copa do Brasil - 2023</option> </select> </div></th> </tr> </thead> </table>
切换下拉框选项后,页面显示的文本会变化,但HTML里的select元素完全没更新——第一个option依然保留selected="selected"属性。之前尝试用BeautifulSoup解析页面源码取值,代码如下但未成功:
soup = BeautifulSoup(driver.page_source, 'html.parser') season_opt = soup.select('table.section-dropdowns select[name="competition_id"]')[0] season = season_opt.text.strip()
可行解决方案
1. 定位显示选中值的可视化元素
这类下拉框大多是自定义模拟组件:原生select可能被隐藏,实际展示选中值的是外层的div元素。直接定位该元素获取文本即可:
# 定位展示选中值的div,提取文本 selected_text = driver.find_element(By.CLASS_NAME, "active-dropdown").text.strip()
2. 用JavaScript获取实际选中状态
页面切换选项后,JS会维护真实的选中状态,即便option的selected属性没更新,select的selectedIndex也会同步变化。直接执行JS脚本获取正确值:
# 获取选中项的value值 selected_value = driver.execute_script("return document.querySelector('select[name=\"competition_id\"]').value;") # 获取选中项的显示文本 selected_text = driver.execute_script(""" var select = document.querySelector('select[name="competition_id"]'); return select.options[select.selectedIndex].text; """)
3. 监控AJAX请求参数(备选)
如果切换选项后页面通过AJAX加载新统计数据,也可以抓取请求参数里的competition_id值,但这种方法复杂度较高,优先使用前两种方案。
内容的提问来源于stack exchange,提问作者Digital Farmer
相关产品推荐
相关产品推荐

