I am trying to search for an element of class "itemavailable" in a table. If its present then click it if not go to the next row and search again in a column.
Here is the HTML code.
My code to search is here click is here. I have calculated the rows and column and also constructed the FinalXpath
for t_row in range(2, (num_rows)):
for t_col in range (3, 4):
FinalXPath = before_XPath str(t_row) aftertd_XPath str(t_col) aftertr_XPath "[@class='itemavailable']"
print(FinalXPath)
try:
if driver.find_element(By.XPATH,"FinalXPath"):
print("found")
avslot = driver.find_element_by_xpath(FinalXPath)
avslot.click()
slot_found = True
break
except NoSuchElementException:
print("not matched")
pass
The output is as follows.
//*[@id='slotsGrid']/tbody/tr[2]/td[3][@class='itemavailable']
not matched
//*[@id='slotsGrid']/tbody/tr[3]/td[3][@class='itemavailable']
not matched
//*[@id='slotsGrid']/tbody/tr[4]/td[3][@class='itemavailable']
not matched
//*[@id='slotsGrid']/tbody/tr[5]/td[3][@class='itemavailable']
not matched
//*[@id='slotsGrid']/tbody/tr[6]/td[3][@class='itemavailable']
not matched
//*[@id='slotsGrid']/tbody/tr[7]/td[3][@class='itemavailable']
not matched
//*[@id='slotsGrid']/tbody/tr[8]/td[3][@class='itemavailable']
not matched
//*[@id='slotsGrid']/tbody/tr[9]/td[3][@class='itemavailable']
not matched
//*[@id='slotsGrid']/tbody/tr[10]/td[3][@class='itemavailable']
not matched
there is a match but not sure why its passing it.
CodePudding user response:
It might not be the best or the most optimized solution, but I would use the find_elements_by_xpath
function (plural), which returns a list.
If the list is not empty, you can click on the first element. Using this method, you can avoid using NoSuchElementException
.
if len(results) > 0
results[0].click()
CodePudding user response:
If, as you said, you only need to find elements with the class itemavailable
in a given table and if the table structure is like you showthen it will be easier to use a search by id and class name:
grid = driver.find_element(By.ID, 'slotsGrid')
items = grid.find_elements(By.CLASS_NAME, 'itemavalible')
for item in items:
item.click()
Your table:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div >
<table id="slotsGrid">
<tbody>
<tr></tr>
<tr>
<td >9:00</td>
<td >...</td>
<td >
<span ><a href="http://" target="_blank">item-1</a></span>
</td>
<td >...</td>
<td >...</td>
<td >
<span ><a href="http://" target="_blank">item-2</a></span>
</td>
<td >...</td>
<td >...</td>
</tr>
<tr>
<td >9:00</td>
<td >...</td>
<td >
<span ><a href="http://" target="_blank">item-3</a></span>
</td>
<td >...</td>
<td >...</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>