[英]How to print the text of the preselected option in a dropdown menu with Selenium using Python?
[英]How to extract the text of the selected option of a Dropdown Menu using Selenium and Python
我正在尝试选择屏幕截图中圈出的菜单选项的文本。 在这种情况下,它是“年龄硬化”。
我能得到的最好的selected value
是17043
的selected value
,而不是文本 'Age Harden'。
这是我尝试过的:
driver.find_element_by_xpath("//select[@id='lstOperation_Key']").get_attribute('text_content')
返回None
driver.find_element_by_xpath("//select[@id='lstOperation_Key']").get_attribute('value')
返回17043
driver.find_element_by_xpath("//select[@id='lstOperation_Key']").get_attribute('text')
返回None
driver.find_element_by_xpath("//select[@id='lstOperation_Key']").get_attribute('selected value')
返回None
my_furnace_parameters_data['Furnace_Operation'] = driver.find_element_by_xpath("//select[@id='lstOperation_Key']//option[1]").get_attribute('text')
返回 'Age Harden',但是,当我在一个不是列表上第一个的操作上进行测试时,比如“动物园治疗”,它是否失败了 - 它仍然返回“老化”。
使用Select
类:
from selenium.webdriver.support.select import Select
operation_key = Select(driver.find_element_by_id('lstOperation_Key'))
operation_key.select_by_visible_text('Age Harden')
# operation_key.select_by_value('17043')
# operation_key.select_by_index(1)
您可以使用WebDriverWait
等待元素可访问:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
operation_key = Select(wait.until(EC.element_to_be_clickable((By.ID, 'lstOperation_Key'))))
operation_key.select_by_visible_text('Age Harden')
# operation_key.select_by_value('17043')
# operation_key.select_by_index(1)
first_selected_option()
返回此选择标记中的第一个选定选项(或普通选择中当前选定的选项)。
看来你已经很接近了。 要提取默认选定<option>
的textContent ,您可以使用first_selected_option
属性来标识元素,您可以按照以下解决方案提取选项文本:
代码块:
select = Select(WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//select[@id='lstOperation_Key' and @name='lstOperation_Key']")))) //selecting tag element = select.first_selected_option print(element.text) # or print(element.get_attribute("innerHTML"))
使用也可以使用这个代码
location_text = ""
location_texts = driver.find_element(By.ID, "select id").find_elements(By.TAG_NAME, "option")
for ii in location_texts:
if str(location_value) == str(ii.get_attribute("value")):
location_text = ii.text
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.