简体   繁体   中英

xpath to get element a label is for (selenium python)

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.

在此处输入图像描述

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

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.

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()

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