Home > Software engineering >  Selenium with Python: select (and click) an element from a table
Selenium with Python: select (and click) an element from a table

Time:03-18

I can't figure out why this don't work. The ID is obviously "ReservedDateTime_2022-08-29 14:10:00"

your help would be much appreciated

Index.html

<div data-function="timeTableCell" data-sectionid="40" data-servicetypeid="632" data-fromdatetime="2022-08-29 14:10:00"  style="top: 620px; height:20px; background-color: #1862a8;color:#ffffff; position:relative;" aria-label="2022-08-29 14:10:00" role="row">

                            <script type="text/javascript">
                                                            document.writeln('14:10');
                            </script>14:10

                            <noscript>

                                            <label  for="ReservedDateTime_2022-08-29 14:10:00">
                                                            <input type="radio" id="ReservedDateTime_2022-08-29 14:10:00" name="ReservedDateTime" value="2022-08-29 14:10:00"  />
                                                            14:10
                                            </label>
                            </noscript>
            </div>

Python

time.sleep(5)
driver.find_element_by_id("ReservedDateTime_2022-08-29 14:10:00").click()
>>
NoSuchElementException: no such element: Unable to locate element: {"method":"css     selector","selector":"[id="ReservedDateTime_2022-08-29 14:10:00"]"}
(Session info: chrome=99.0.4844.74)

The div is inside an tbody

CodePudding user response:

This id

ReservedDateTime_2022-08-29 14:10:00

looks dynamic in nature since it has date and time.

I'd recommend you to use name instead:

name="ReservedDateTime"

or

CSS:

input[name='ReservedDateTime']

or XPath:

//input[@name='ReservedDateTime']

PS : Please check in the dev tools (Google chrome) if we have unique entry in HTML DOM or not.

Steps to check:

Press F12 in Chrome -> go to element section -> do a CTRL F -> then paste the //input[@name='ReservedDateTime'] and see, if your desired element is getting highlighted with 1/1 matching node.

You can click it like below:

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[@name='ReservedDateTime']"))).click()

Imports:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

CodePudding user response:

Datetime may be dynamic for each instance, try with name instead.

driver.find_element(By.NAME, 'ReservedDateTime')
  • Related