Home > Software engineering >  xpath to get element a label is for (selenium python)
xpath to get element a label is for (selenium python)

Time:11-18

I'm using the python package selenium to write a script that will automatically set up appointments for myself every week. What I ultimately want here is to be able to click the button with id="1103222339". I initally tried driver.find_element_by_id("1103222339").click(), but I cannot guarentee that every time I run this script that the appointment I need will correspond to this ID. To solve this issue, I want to look at the label that has text specifying the time and date of the appointment I want, then to somehow retrieve the id through that for value.

enter image description here

I have not used xpath before, how do I find the element that a label is for through its text?

CodePudding user response:

You can build XPath expression locating the target input element based on the time, as following:

driver.find_element_by_xpath("//tr[.//label[contains(text(),'November 24, 2021 3:20 PM')]]//input").click()

Here you can, of cause, set the desired text according to your needs.
The XPath I built means: "locate tr element that has inside it a label element that contains November 24, 2021 3:20 PM' text. So inside this tr find an input element."
This is what you need here.

CodePudding user response:

To click on the <input> button element you can't use the id="1103222339" as it is dynamically generated and would change every time you access the application.

To click on the element you can use either of the following Locator Strategies:

  • Using css_selector:

    driver.find_element(By.CSS_SELECTOR, "a.StrongText[for]").click()
    
  • Using xpath:

    driver.find_element(By.XPATH, "//label[@for and @class='StrongText'][contains(., 'November 24, 2021 3:20 PM')]").click()
    
  • Related