Python Forum
[Selenium] Xpath Drop Down Use Variable
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Selenium] Xpath Drop Down Use Variable
#1
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
Reply
#2
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']"
Reply
#3
(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?
Reply
#4
String formatting, so that it prints 02, instead of 2
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Selenium XPATH jimsxxl 2 2,941 Apr-06-2021, 03:19 PM
Last Post: jimsxxl
  Selenium: accessing a drop-down menus without select tags ClassicalSoul 0 2,029 Apr-19-2020, 03:53 PM
Last Post: ClassicalSoul
  need help with xpath pythonprogrammer 1 2,731 Jan-18-2020, 11:28 PM
Last Post: snippsat
  Selenium xpath finding gif to click fyec 1 3,761 Jul-27-2018, 05:20 PM
Last Post: snippsat
  Proxy Variable in Selenium wont work with FireFox Profile Proxy Setting. MIPython 0 8,491 Jul-13-2018, 05:43 PM
Last Post: MIPython
  Error in Selenium: CRITICAL:root:Selenium module is not installed...Exiting program. AcszE 1 3,584 Nov-03-2017, 08:41 PM
Last Post: metulburr
  Click on a Drop-down button with selenium Python AcszE 3 7,283 Oct-25-2017, 03:13 PM
Last Post: vardhhan

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020