简体   繁体   中英

How to randomly select from a drop-down menu using selenium?

I'm pretty new to python 3 and have been learning to automate some of my web task I do using selenium.

So say their are 3 drop-down list on the page, Month, Day, & Year. When selecting a drop-down menu, how exactly can I randomly select a option listed in the menu?

    month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
             'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    day = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'
           '11', '12', '13', '14', '15', '16', '17', '18', '19', '20'
           '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31']
    year = ['1996', '1995', '1994', '1993', '1992', '1991', '1990', '1989', '1998' ]

    Select(driver.find_element_by_css_selector('#month')).select_by_visible_text('Jun')
    Select(driver.find_element_by_css_selector('#day')).select_by_visible_text('13')
    Select(driver.find_element_by_css_selector('#year')).select_by_visible_text('1981')

is the code I have so far. Is their a way to select_by_visible_text randomly is basically what I'm asking?

You can use random.choice , so your code would be:

import random    

month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
         'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
day = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'
       '11', '12', '13', '14', '15', '16', '17', '18', '19', '20'
       '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31']
year = ['1996', '1995', '1994', '1993', '1992', '1991', '1990', '1989', '1998' ]

Select(driver.find_element_by_css_selector('#month')).select_by_visible_text(random.choice(month))
Select(driver.find_element_by_css_selector('#day')).select_by_visible_text(random.choice(month))
Select(driver.find_element_by_css_selector('#year')).select_by_visible_text(random.choice(year))

Just use select_by_index(i) where i is randomly selected from the number of available options in the dropdown. It will be more flexible and you won't have to maintain a list of months, days, years... and deal with leap years or months with varying days, 28 v 30 v 31, etc.

month = Select(driver.find_element_by_css_selector('#month'))
month.select_by_index(randint(0, len(month.options) - 1))

I might suggest that you print/log the random options selected during a run. If you ever run into an issue, you'll need that info to reproduce or investigate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM