Home > Net >  How to iterate over XPATH using only even index in a FOR loop
How to iterate over XPATH using only even index in a FOR loop

Time:08-25

This is a snippet of my code

alternative_solutions = driver.find_elements(By.CLASS_NAME, "flight-row")
                positive("Total number of Alternative options found are {}".format(len(alternative_solutions)))

k = 1
for j in range(2, len(alternative_solutions),2):
   flight_number = WebDriverWait(driver, 20).until(EC.presence_of_element_located((By.XPATH, "//hgb-alternative-flights[1]/div[2]/div[1]/div[1]/div[1]/table[1]/tr[{}]/td[2]" .format(j)))).text

I am trying to iterate over a table and capture the values using the for loop. The table in question has 10 solutions (lets suppose). Each of the solution I can iterate over the XPATH.

The problem here is that the solutions are only available on the even number i.e I can iterate over only 2,4,6 and so on.

With the for loop that I have, I am able to iterate 4 times and then the loop exits.

How do I handle this gracefully

The HTML looks like where ng-star-inserted is only for spacing

<table _ngcontent-vxq-c254 xpath="1"> == $0
    <tr _ngcontent-vxq-c254 >..</tr>
    <!---->
    <tr _ngcontent-vxq-c254 >..</tr>
    <!---->
    <tr _ngcontent-vxq-c254 >..</tr>
    <!---->
    <tr _ngcontent-vxq-c254 >..</tr>
    <!---->
</table>

CodePudding user response:

Maybe

for j in range(2, len(alternative_solutions)   2, 2):
    ...

As you remember,range() includes the start value but excluding the end one

CodePudding user response:

Consider making the XPath expression more selective:

(/my/path/expression)[position() mod 2 = 0]
  • Related