Python Forum

Full Version: [Selenium] Xpath Drop Down Use Variable
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I wanted to have a variable (random number between 1 and 12) used for my drop down option value..

So instead of value='05' it would be something like value='month', value='day'

Unfortunately it doesn't work. What are my options?

driver.find_element_by_xpath("//SELECT[@name='month']/option[@value='05']").click()
driver.find_element_by_xpath("//SELECT[@name='day']/option[@value='01']").click()
PS - the numbers must be formatted like 01, 02, 03, 04, 05, 06 etc rather than 1, 2, 3, 4, 5
if I get right you want to get random number to be used in the xpath.
>>> from random import randint
>>> month = randint(1, 12)
>>> my_xpath="//SELECT[@name='month']/option[@value='{:0>2}']"
>>> my_xpath.format(month)
"//SELECT[@name='month']/option[@value='12']"
(Oct-07-2017, 06:34 AM)buran Wrote: [ -> ]if I get right you want to get random number to be used in the xpath.
>>> from random import randint
>>> month = randint(1, 12)
>>> my_xpath="//SELECT[@name='month']/option[@value='{:0>2}']"
>>> my_xpath.format(month)
"//SELECT[@name='month']/option[@value='12']"

Hi Buran, thanks for sharing the solution!

This is the only part that confuses me:

{:0>2}
What does that do?
String formatting, so that it prints 02, instead of 2