python-3.xselenium-webdriver

selenium - select table columns by xpath not work


I would like to select table columns like below:

    <div data-v-5b5efb54="" data-cy=".." class="table-columns">
      <div data-v-5b5efb54=""><a data-v-5b5efb54=""
          href="/artifactory/sample/"
          data-cy="url-to-file">
          ../
        </a></div>
      <div data-v-5b5efb54=""></div>
      <div data-v-5b5efb54=""></div>
      <div data-v-5b5efb54=""><span data-v-5b5efb54=""></span></div>
    </div>
    <div data-v-5b5efb54="" data-cy="1.10.1" class="table-columns">
      <div data-v-5b5efb54=""><a data-v-5b5efb54=""
          href="/artifactory/1.10.1/"
          data-cy="url-to-file">
          1.10.1/
        </a></div>
      <div data-v-5b5efb54="">14-May-2024 17:40:58 -0500</div>
      <div data-v-5b5efb54=""></div>
      <div data-v-5b5efb54=""><span data-v-5b5efb54=""></span></div>
    </div>

I try to select the table-columns class firstly, then iterate elements under it.

    columns = driver.find_elements(By.XPATH,"(//div[@class='table-columns'])")
    print(len(columns))
   
    for column in columns:
        cell1 = column.find_element(By.XPATH,"//div[1]/a")
        cell2 = column.find_element(By.XPATH,"//div[2]")
        cell3 = column.find_element(By.XPATH,"//div[3]")
        cell4 = column.find_element(By.XPATH,"//div[4]")       
     print(cell1.get_attribute('href'),cell2.text,cell3.text,cell4.text)

Current code loops repeatly.


Solution

  • When you use //div/a, it searches for the first <a> element in the entire document, not relative to the current column element. You should use a dot . at the beginning of the XPath to make it relative to the current element.

    columns = driver.find_elements(By.XPATH, "//div[@class='table-columns']")
    print(len(columns))
    
    for column in columns:
        cell1 = column.find_element(By.XPATH, ".//div/a")
        cell2 = column.find_element(By.XPATH, ".//div")
        cell3 = column.find_element(By.XPATH, ".//div")
        cell4 = column.find_element(By.XPATH, ".//div")
        print(cell1.get_attribute('href'), cell2.text, cell3.text, cell4.text)