How to search for specific text within HTML cell event and click corresponding button within same cell?

Viewed 32

Need some help with my first python project (also my first post on stackoverflow). Appreciate your time and help!

I am trying to automate regular booking on a website using selenium and chrome webdriver. The booking page is a timetable, with each cell corresponding to a timeslot and "Book" buttons within each cell/timeslot.

However, the XPATH for these buttons turns out to be dynamic.

E.g. //*[@id="root"]/div[4]/div/div[4]/div/div[3]/div[69]/div[3]/button

Each cell and button for the different timeslots has the same html class name and type. So would it be possible to search for the text in each cell (e.g. Class 1.10 7:30) and click the corresponding button within the same cell?

<div class="column">
  <div class="cell  even">
    <span class="d-block d-sm-none">Sat, 17th Jul</span>
    <span class="d-none d-sm-block">Saturday, 17th July</span></div>

  <div class="cell event " style="color: rgb(255, 255, 255); top: 8rem; height: 6rem;">
    <div>Class 1.1</div>
    <div>07:30</div>
    <div class="position-relative">
      <button class="btn btn-warning" type="button">Book</button>
    </div>
  </div>
    
  <div class="cell event " style="color: rgb(255, 255, 255); top: 16rem; height: 6rem;">
    <div>Class 1.2</div>
    <div>08:30</div>
    <div class="position-relative">
      <button class="btn btn-warning" type="button">Book</button>
      </div>
    </div>
1 Answers

Yes, it is possible.
If you want to match 2 texts in 2 elements as shown in the HTML you presented and I guess the texts are passed to the method as parameters, it will be something like this:

btn_xpath = ("//div[./div[contains(text(),'Class $class')] and (./div[contains(text(),'$time')])]//button[text()='Book']",(class=class, time=time))
driver.find_element_by_xpath(btn_xpath).click()

Here class and time are parameters passed from outside to select the desired class and time.
In case the selection can be unique by the time only it will be like this:

btn_xpath = ("//div[./div[contains(text(),'$time')]]//button[text()='Book']",(time=time))
driver.find_element_by_xpath(btn_xpath).click()
Related