英文:
How to get the value attribute of the selected option in a dropdown using selenium with python?
问题
我有一个使用Python的Selenium代码,它使用Selenium中的'Select'包的select_by_value方法在下拉列表中选择一个值。
如图所示,在图片中,我在代码中输入值 1
,然后它选择了与值 1
关联的文本“Poste”。
我的问题是在选择过程之后是否有一种方法可以获取所选的值。
我知道使用first_selected_option方法,我可以获取所选选项的文本:
selected_value = options_com.first_selected_option
sv = selected_value.text
print(sv)
那么是否有一种方法可以返回所选的值,例如在此示例中的value = "1"
,而不是文本。
英文:
I have a selenium code (using python) that select a value in a dropdown using the select_by_value method of the 'Select' package in selenium.
As you can see in the picture, I input the value 1
in the code and it selects "Poste" which is the text associated with the value 1
.
My question is if there is a way to get the value that was selected after the select process.
I know that with the first_selected_option method I can go get the text of the option selected with :
selected_value = options_com.first_selected_option
sv = selected_value.text
print(sv)
So is there a way to return the value selected, in this exemple the value = "1"
, instead of the text.
答案1
得分: 1
The first_selected_option
属性返回选择标签中的第一个选定选项(或正常选择中当前选定的选项)。
解决方案
要打印所选选项的_value属性的值,您可以使用get_attribute()
方法,如下所示:
select = Select(driver.find_element(By.XPATH, "//select[@id='client.select.communication']))
select.select_by_value("1")
print(select.first_selected_option.get_attribute("value")) # 打印 -> 1
注意:您必须添加以下导入:
from selenium.webdriver.common.by import By
英文:
The first_selected_option
attribute returns the first selected option in this select tag (or the currently selected option in a normal select).
Solution
To print the value of the value attribute of the selected option you can use the get_attribute()
method as follows:
select = Select(driver.find_element(By.XPATH, "//select[@id='client.select.communication']))
select.select_by_value("1")
print(select.first_selected_option.get_attribute("value")) # prints -> 1
Note : You have to add the following imports :
from selenium.webdriver.common.by import By
答案2
得分: 0
你可以使用常规的 get_attribute()
函数。
select = Select(driver.find_element(By.CSS_SELECTOR, "yout_selector"))
select.select_by_visible_text("visible_text")
selected_option = select.first_selected_option
option_value = selected_option.get_attribute("value")
print("所选选项的值为:" + option_value)
first_selected_option
属性将项转换为 Webelement,因此您可以使用常规的 Webelement 函数执行任何操作。
英文:
you can use regular get_attribute()
function
select = Select(driver.find_element(By.CSS_SELECTOR, "yout_selector"))
select.select_by_visible_text("visible_text")
selected_option = select.first_selected_option
option_value = selected_option.get_attribute("value")
print("Value of selected option is:" + option_value )
first_selected_option
propert convert item into Webelement. so, you can use regular Webelement functions to do any operation you want.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论