如何用Python的Selenium获取下拉菜单选中项的显示文本?
如何通过Selenium获取下拉选中项的显示文本?
下拉菜单HTML结构
<option label="John Smith" value="string:0012">John Smith</option> <option label="John Doe" value="string:0001" selected="selected">John Doe</option>
现有尝试代码
try: SelectedUser = driver.find_element("xpath", '//*[@id="some-content"]/div/form/div[3]/div/div/select').get_attribute("value"); print(SelectedUser) except NoSuchElementException: SelectedUser= "Not Available"
当前通过get_attribute("value")能获取选中项的value值(如string:0001),但需要获取显示文本(如John Doe),尝试get_attribute("label")返回None,求解决方法。
解决方案
方法1:直接定位选中的option元素获取文本
直接定位带有selected属性的option子元素,调用.text属性即可获取显示文本:
try: selected_option = driver.find_element("xpath", '//*[@id="some-content"]/div/form/div[3]/div/div/select/option[@selected="selected"]') SelectedUser = selected_option.text print(SelectedUser) except NoSuchElementException: SelectedUser = "Not Available"
方法2:使用Selenium的Select类(推荐)
Selenium提供了专门处理下拉框的Select类,操作更规范简洁:
from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException try: select_element = driver.find_element("xpath", '//*[@id="some-content"]/div/form/div[3]/div/div/select') select = Select(select_element) # 获取第一个选中的选项对象,再提取文本 SelectedUser = select.first_selected_option.text print(SelectedUser) except NoSuchElementException: SelectedUser = "Not Available"
补充说明
你之前用get_attribute("label")返回None,是因为该方法是在select元素上调用的,但label属性属于option子元素,而非select元素本身。即便定位到option元素后调用get_attribute("label")能拿到值,也不如.text属性可靠——因为.text直接获取的是option标签内的显示内容,和页面上展示的文本完全一致。
内容的提问来源于stack exchange,提问作者Acuity
相关产品推荐
相关产品推荐

