如何使用 Python 使用 Selenium 选择下拉菜单值?

发布于 2024-12-11 05:45:45 字数 640 浏览 0 评论 0 原文

我需要从下拉菜单中选择一个元素。

例如:

<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(...) 来完成此操作,但它不起作用。

I need to select an element from a drop-down menu.

For example:

<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) First I have to click on it. I do this:

inputElementFruits = driver.find_element_by_xpath("//select[id='fruits']").click()

2) After that I have to select the good element, lets say Mango.

I tried to do it with inputElementFruits.send_keys(...) but it did not work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

熟人话多 2024-12-18 05:45:45

Selenium 提供了一个方便的 Selectselect -> 一起使用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 provides a convenient Select class to work with select -> option constructs:

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')

See also:

强者自强 2024-12-18 05:45:45

除非您的点击触发某种 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/无法使用seleniums-python-webdriver选择选项

Unless your click is firing some kind of ajax call to populate your list, you don't actually need to execute the click.

Just find the element and then enumerate the options, selecting the option(s) you want.

Here is an example:

from selenium import webdriver
b = webdriver.Firefox()
b.find_element_by_xpath("//select[@name='element_name']/option[text()='option_text']").click()

You can read more in:
https://sqa.stackexchange.com/questions/1355/unable-to-select-an-option-using-seleniums-python-webdriver

心头的小情儿 2024-12-18 05:45:45

我希望这段代码能对您有所帮助。

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'))

从下拉列表中选择“Banana”

  1. 使用下拉列表的索引

ddelement.select_by_index(1)

  1. 使用下拉列表的值

ddelement.select_by_value('1')

  1. 您可以使用匹配下拉列表中显示的文本。

ddelement.select_by_visible_text('香蕉')

I hope this code will help you.

from selenium.webdriver.support.ui import Select

dropdown element with id

ddelement= Select(driver.find_element_by_id('id_of_element'))

dropdown element with xpath

ddelement= Select(driver.find_element_by_xpath('xpath_of_element'))

dropdown element with css selector

ddelement= Select(driver.find_element_by_css_selector('css_selector_of_element'))

Selecting 'Banana' from a dropdown

  1. Using the index of dropdown

ddelement.select_by_index(1)

  1. Using the value of dropdown

ddelement.select_by_value('1')

  1. You can use match the text which is displayed in the drop down.

ddelement.select_by_visible_text('Banana')

眼眸 2024-12-18 05:45:45

首先,您需要导入 Select 类,然后需要创建 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)

firstly you need to import the Select class and then you need to create the instance of Select class.
After creating the instance of Select class, you can perform select methods on that instance to select the options from dropdown list.
Here is the code

from selenium.webdriver.support.select import Select

select_fr = Select(driver.find_element_by_id("fruits01"))
select_fr.select_by_index(0)
柠檬色的秋千 2024-12-18 05:45:45

根据提供的 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>

菜单,您必须使用 选择 。此外,由于您必须与 你必须诱导WebDriverWait element_to_be_clickable()

您可以使用以下任一定位器策略

  • 使用ID 属性和 select_by_visible_text() 方法:

    从 selenium 导入 webdriver
    从 selenium.webdriver.support.ui 导入 WebDriverWait
    从 selenium.webdriver.common.by 导入
    从 selenium.webdriver.support 导入预期条件作为 EC
    从 selenium.webdriver.support.ui 导入 选择
    
    select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "fruits01"))))
    select.select_by_visible_text("芒果")
    
  • 使用CSS-SELECTORselect_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")
    
  • 使用XPATHselect_by_index()方法:< /p>

    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)
    

As per the HTML provided:

<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>

To select an <option> element from a menu you have to use the Select Class. Moreover, as you have to interact with the you have to induce WebDriverWait for the element_to_be_clickable().

To select the <option> with text as Mango from the you can use you can use either of the following Locator Strategies:

  • Using ID attribute and select_by_visible_text() method:

    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")
    
  • Using CSS-SELECTOR and select_by_value() method:

    select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "select.select[name='fruits']"))))
    select.select_by_value("2")
    
  • Using XPATH and select_by_index() method:

    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)
    
终陌 2024-12-18 05:45:45

我尝试了很多事情,但我的下拉菜单位于表格内,我无法执行简单的选择操作。只有下面的解决方案有效。在这里,我突出显示下拉 elem 并按向下箭头,直到获得所需的值 -

#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)

I tried a lot many things, but my drop down was inside a table and I was not able to perform a simple select operation. Only the below solution worked. Here I am highlighting drop down elem and pressing down arrow until getting the desired value -

#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)
柠檬色的秋千 2024-12-18 05:45:45

您无需单击任何内容。
使用 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")

就是这样。

You don't have to click anything.
Use find by xpath or whatever you choose and then use send keys

For your example:
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")

That's it.

(り薆情海 2024-12-18 05:45:45

您可以使用 css 选择器组合,

driver.find_element_by_css_selector("#fruits01 [value='1']").click()

将 css 选择器 attribute = value 中的 1 更改为与所需水果对应的值。

You can use a css selector combination a well

driver.find_element_by_css_selector("#fruits01 [value='1']").click()

Change the 1 in the attribute = value css selector to the value corresponding with the desired fruit.

海夕 2024-12-18 05:45:45

通过这种方式,您可以选择任何下拉列表中的所有选项。

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)

In this way you can select all the options in any dropdowns.

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)
心房敞 2024-12-18 05:45:45

在浏览了很多像这样的帖子之后,我设法找到了一种解决方案,允许我在下拉列表中选择一个项目。我以各种方式尝试了 .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 完成的。

After going through a lot of posts like this one, I managed to figure out a solution that allowed me to select an item in a dropdown. I tried .send_keys, click(), and Select in various ways with no success. Ended up sending the click() command to the dropdown 3 times before clicking on the item in the dropdown.

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()

Definitely not super pretty, but it works.

Hope this helps someone. This was done with Python3.7.7 on Firefox 88.0.1.

秋意浓 2024-12-18 05:45:45

使用以下方式您可以选择下拉值。

select=browser.find_element(by=By.XPATH,value='path to the dropdown')
 select.send_keys("Put value here to select it")

Using Following Way You can Select the dropdown value.

select=browser.find_element(by=By.XPATH,value='path to the dropdown')
 select.send_keys("Put value here to select it")
两相知 2024-12-18 05:45:45

它适用于选项值:

from selenium import webdriver
b = webdriver.Firefox()
b.find_element_by_xpath("//select[@class='class_name']/option[@value='option_value']").click()

It works with option value:

from selenium import webdriver
b = webdriver.Firefox()
b.find_element_by_xpath("//select[@class='class_name']/option[@value='option_value']").click()
晨光如昨 2024-12-18 05:45:45

我将其用于所有点击和选择,并且它始终有效。对于下拉项,只需确保 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()

I use this for all of my clicks and selecting and it always works. For a dropdown item just make sure the xpath is the actual value you want to select.

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()
无畏 2024-12-18 05:45:45
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)

它会工作得很好

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)

It will work fine

水水月牙 2024-12-18 05:45:45

没有

每次我面对没有

# Finds the dropdown option by its text
driver.find_element_by_xpath("//*[text()='text of the option']")

导入 ActionChains module

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()

Dropdown WITHOUT <select>

This works for me every time I face a dropdown without <select> tags

# Finds the dropdown option by its text
driver.find_element_by_xpath("//*[text()='text of the option']")

Import ActionChains module

from selenium.webdriver.common.action_chains import ActionChains

Use ActionChains to click on the element

drp_element = driver.find_element_by_xpath("//*[text()='text of the option']")
action = ActionChains(driver)
action.click(on_element=drp_element).perform()
初雪 2024-12-18 05:45:45

它对我的情况有效的唯一方法是:

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()

所有其他解决方案都不起作用,因为该值总是立即重置。

The only way it worked for my case was:

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()

All the other solutions didnt work as the value always resetted immediately.

久夏青 2024-12-18 05:45:45

使用 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);

The best way to use selenium.webdriver.support.ui.Select class to work to with dropdown selection but some time it does not work as expected due to designing issue or other issues of the HTML.

In this type of situation you can also prefer as alternate solution using execute_script() as below :-

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);
泛泛之交 2024-12-18 05:45:45
dropdown1 = Select(driver.find_element_by_name("fruits"))
dropdown1.select_by_visible_text('banana')
dropdown1 = Select(driver.find_element_by_name("fruits"))
dropdown1.select_by_visible_text('banana')
如何视而不见 2024-12-18 05:45:45
  1. 列表项
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();

    }

}
  1. List item
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();

    }

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文