如何使用 Python 通过 Selenium 选择下拉菜单值?
- 2024-12-04 08:56:00
- admin 原创
- 147
问题描述:
我需要从下拉菜单中选择一个元素。
例如:
<select id="fruits01" class="select" name="fruits">
<option value="0">Choose your fruits:</option>
<option value="1">Banana</option>
<option value="2">Mango</option>
</select>
1)首先我必须点击它。我这样做:
inputElementFruits = driver.find_element_by_xpath("//select[id='fruits']").click()
2)之后我必须选择好的元素,比如说Mango
。
我尝试过这么做inputElementFruits.send_keys(...)
,但没有成功。
解决方案 1:
Selenium 提供了一个方便的Select
类来处理select -> option
构造:
from selenium import webdriver
from selenium.webdriver.support.ui import Select
driver = webdriver.Firefox()
driver.get('url')
select = Select(driver.find_element_by_id('fruits01'))
# select by visible text
select.select_by_visible_text('Banana')
# select by value
select.select_by_value('1')
参见:
选择使用 Selenium 的 Python WebDriver 的正确方法是什么?
解决方案 2:
除非您的点击会触发某种 ajax 调用来填充您的列表,否则您实际上并不需要执行点击。
只需找到元素,然后枚举选项,选择您想要的选项。
以下是一个例子:
from selenium import webdriver
b = webdriver.Firefox()
b.find_element_by_xpath("//select[@name='element_name']/option[text()='option_text']").click()
您可以在以下网址阅读更多信息: https:
//sqa.stackexchange.com/questions/1355/unable-to-select-an-option-using-seleniums-python-webdriver
解决方案 3:
我希望这段代码能够帮助你。
from selenium.webdriver.support.ui import Select
带 id 的下拉元素
ddelement= Select(driver.find_element_by_id('id_of_element'))
带有 xpath 的下拉元素
ddelement= Select(driver.find_element_by_xpath('xpath_of_element'))
带有 CSS 选择器的下拉元素
ddelement= Select(driver.find_element_by_css_selector('css_selector_of_element'))
从下拉菜单中选择“香蕉”
使用下拉列表的索引
ddelement.select_by_index(1)
使用下拉列表的值
ddelement.select_by_value('1')
您可以使用匹配下拉菜单中显示的文本。
ddelement.select_by_visible_text('Banana')
解决方案 4:
首先,您需要导入 Select 类,然后需要创建 Select 类的实例。创建 Select 类的实例后,您可以在该实例上执行选择方法,以从下拉列表中选择选项。以下是代码
from selenium.webdriver.support.select import Select
select_fr = Select(driver.find_element_by_id("fruits01"))
select_fr.select_by_index(0)
解决方案 5:
根据提供的 HTML:
<select id="fruits01" class="select" name="fruits">
<option value="0">Choose your fruits:</option>
<option value="1">Banana</option>
<option value="2">Mango</option>
</select>
要从<option>
中选择一个元素html 选择菜单,您必须使用选择 类。此外,由于您必须与下拉式菜单你必须诱导WebDriverWaitelement_to_be_clickable()
。
要从中选择<option>
文本为Mango 的下拉列表您可以使用以下任一定位器策略:
使用ID属性和
select_by_visible_text()
方法:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select
select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "fruits01"))))
select.select_by_visible_text("Mango")
使用CSS-SELECTOR和
select_by_value()
方法:
select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "select.select[name='fruits']"))))
select.select_by_value("2")
使用XPATH和
select_by_index()
方法:
select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "//select[@class='select' and @name='fruits']"))))
select.select_by_index(2)
解决方案 6:
我尝试了很多方法,但我的下拉列表位于表格内,我无法执行简单的选择操作。只有下面的解决方案有效。在这里,我突出显示下拉元素并按下向下箭头直到获得所需的值 -
#identify the drop down element
elem = browser.find_element_by_name(objectVal)
for option in elem.find_elements_by_tag_name('option'):
if option.text == value:
break
else:
ARROW_DOWN = u'/ue015'
elem.send_keys(ARROW_DOWN)
解决方案 7:
您无需单击任何内容。使用 xpath 查找或您选择的任何内容,然后使用发送键
例如:HTML:
<select id="fruits01" class="select" name="fruits">
<option value="0">Choose your fruits:</option>
<option value="1">Banana</option>
<option value="2">Mango</option>
</select>
Python:
fruit_field = browser.find_element_by_xpath("//input[@name='fruits']")
fruit_field.send_keys("Mango")
就是这样。
解决方案 8:
您可以使用 css 选择器组合
driver.find_element_by_css_selector("#fruits01 [value='1']").click()
将属性 = 值 css 选择器中的 1 更改为与所需水果相对应的值。
解决方案 9:
通过这种方式,您可以选择任何下拉菜单中的所有选项。
driver.get("https://www.spectrapremium.com/en/aftermarket/north-america")
print( "The title is : " + driver.title)
inputs = Select(driver.find_element_by_css_selector('#year'))
input1 = len(inputs.options)
for items in range(input1):
inputs.select_by_index(items)
time.sleep(1)
解决方案 10:
在阅读了大量类似这样的帖子后,我终于找到了一个解决方案,让我可以在下拉菜单中选择一项。我尝试了 .send_keys、click() 和 Select 等各种方法,但都没有成功。最后,我向下拉菜单发送了 3 次 click() 命令,然后才单击下拉菜单中的项。
dropMenu = browser.find_element_by_id('cmbDeviceType')
dropMenu.click()
dropMenu.click()
dropMenu.click()
deviceType = browser.find_element_by_id('cmbDeviceType_DDD_L_LBI16T0')
deviceType.click()
虽然不是非常漂亮,但是确实很管用。
希望这对某人有帮助。这是使用 Firefox 88.0.1 上的 Python3.7.7 完成的。
解决方案 11:
使用以下方式您可以选择下拉值。
select=browser.find_element(by=By.XPATH,value='path to the dropdown')
select.send_keys("Put value here to select it")
解决方案 12:
它与选项值一起使用:
from selenium import webdriver
b = webdriver.Firefox()
b.find_element_by_xpath("//select[@class='class_name']/option[@value='option_value']").click()
解决方案 13:
我使用它来进行所有的点击和选择,它总是有效的。对于下拉项,只需确保 xpath 是您想要选择的实际值即可。
var = WebDriverWait(driver, explicit_wait_seconds).until(
EC.element_to_be_clickable((By.XPATH, self)))
# added the click here.
ActionChains(driver).move_to_element(var).click()
perform_actions()
actions.perform()
# Reset was required to clear it. Might be patched now.
actions.reset_actions()
for device in actions.w3c_actions.devices:
device.clear_actions()
解决方案 14:
from selenium.webdriver.support.ui import Select
driver = webdriver.Ie(".\\IEDriverServer.exe")
driver.get("https://test.com")
select = Select(driver.find_element_by_xpath("""//input[@name='n_name']"""))
select.select_by_index(2)
它会很好地工作
解决方案 15:
下拉列表无<select>
每当我遇到没有<select>
标签的下拉菜单时,这对我来说都很有用
# Finds the dropdown option by its text
driver.find_element_by_xpath("//*[text()='text of the option']")
导入ActionChains
模块
from selenium.webdriver.common.action_chains import ActionChains
用于ActionChains
点击元素
drp_element = driver.find_element_by_xpath("//*[text()='text of the option']")
action = ActionChains(driver)
action.click(on_element=drp_element).perform()
解决方案 16:
对我而言唯一有效的方法是:
select_option_index = 0
for index, option in enumerate(self.browser.find_element(By.ID, dropdown_id).find_elements(By.TAG_NAME, "option")):
if option.text == desired_value:
select_option_index = index
break
WebDriverWait(self.browser, 10).until(EC.element_to_be_clickable((By.ID, dropdown_id))).click()
self.wait(1)
WebDriverWait(self.browser, 10).until(EC.element_to_be_clickable((By.XPATH, f"/html/body/section/div/section/form/fieldset[2]/div[3]/select/option[{select_option_index + 1}]"))).click()
所有其他解决方案均不起作用,因为值总是立即重置。
解决方案 17:
最好的方法是使用selenium.webdriver.support.ui.Select
类来进行下拉选择,但有时由于设计问题或 HTML 的其他问题,它不能按预期工作。
在这种情况下,您也可以选择使用execute_script()
以下替代解决方案:-
option_visible_text = "Banana"
select = driver.find_element_by_id("fruits01")
#now use this to select option from dropdown by visible text
driver.execute_script("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text == arguments[1]){ select.options[i].selected = true; } }", select, option_visible_text);
解决方案 18:
dropdown1 = Select(driver.find_element_by_name("fruits"))
dropdown1.select_by_visible_text('banana')
解决方案 19:
列表项
public class ListBoxMultiple {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("file:///C:/Users/Amitabh/Desktop/hotel2.html");//open the website
driver.manage().window().maximize();
WebElement hotel = driver.findElement(By.id("maarya"));//get the element
Select sel=new Select(hotel);//for handling list box
//isMultiple
if(sel.isMultiple()){
System.out.println("it is multi select list");
}
else{
System.out.println("it is single select list");
}
//select option
sel.selectByIndex(1);// you can select by index values
sel.selectByValue("p");//you can select by value
sel.selectByVisibleText("Fish");// you can also select by visible text of the options
//deselect option but this is possible only in case of multiple lists
Thread.sleep(1000);
sel.deselectByIndex(1);
sel.deselectAll();
//getOptions
List<WebElement> options = sel.getOptions();
int count=options.size();
System.out.println("Total options: "+count);
for(WebElement opt:options){ // getting text of every elements
String text=opt.getText();
System.out.println(text);
}
//select all options
for(int i=0;i<count;i++){
sel.selectByIndex(i);
Thread.sleep(1000);
}
driver.quit();
}
}