2

So I want to use format to manipulate with timepicker in selenium python.

I have following variable:

time = Element('xpath=//li[contains(text(),"{}:{} PM")]')

And then I try to use format to located the element:

def select_ten_thirty_time(self):
    self.time_picker.wait_element_to_be_clickable().click()
    self.time.format(10, 30).wait_element_to_be_clickable().click()

But I get this error:

selenium.common.exceptions.NoSuchElementException: \
Message: Unable to locate element: //li[contains(text(),"{}:{} PM")]

EDIT => Added HTML

<li class="react-datepicker__time-list-item 
    react-datepicker__time-list-item--selected">10:30 PM</li>

Thank you for your help!

2
  • Can you please add HTML? Commented Oct 11, 2021 at 13:32
  • Hi @NandanA, I edited the question with HTML. thank you Commented Oct 11, 2021 at 13:43

2 Answers 2

2

Please use f string like this :

hour = '10'
sec = '30'
time = driver.find_element_by_xpath(f"//li[contains(text(),'{hour}:{sec}') and contains(text(),'PM')]")

You can have same for AM or PM.

Sign up to request clarification or add additional context in comments.

Comments

1

You need to write a xPath it should work for both AM and PM times.

//li[contains(text(),"10:30 AM") or contains(text(),"10:30 PM")]

Parameterize the time in xPath

//li[contains(text(),"+time+" AM") or contains(text(),"+time+" PM")]

Code:

time = '10:30'
wait.until(EC.element_to_be_clickable((By.XPATH, "//li[contains(text(),"+time+" AM") or contains(text(),"+time+" PM")]")))

2 Comments

Thanks Nandan, what if I want only PM time and how should I properly format the xpath to find the element?
Can you please see updated solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.