如何使用 Python 中的 Selenium WebDriver 获取选中的选项?
我们可以使用 Selenium webdriver 获取下拉框中选定的选项。first_selected_option 方法会获取下拉框中选定的选项。返回该选项后,我们需要应用 text 方法来获取该选项的文本。
让我们考虑这个下拉框 Continents 并获取其选定的项目 −

示例
from selenium import webdriver
from selenium.webdriver.support.select import Select
import time driver = webdriver.Chrome(executable_path="C:\chromedriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://tutorialspoint.com/selenium/selenium_automation_practice.htm")
# identify dropdown
s = Select(driver.find_element_by_xpath("//select[@name='continents']"))
#select by option index
s.select_by_index(4)
#get selected item with method first_selected_option
o= s.first_selected_option
#text method for selected option text
print("Selected option is: "+ o.text)
driver.close()输出

广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP