0
wait.until(EC.presence_of_element_located((By.XPATH, "//table//tbody//tr//a[@data-refid='recordId'][0]")))
driver.implicitly_wait(20)
line_item = driver.find_elements("xpath", "//table//tbody//tr//a[@data-refid='recordId'][0]")
print(line_item)

I need to find the first element in table which is arr[0] but i am finding no element exception.

Ben David
  • 51
  • 5

3 Answers3

0

You can use the find_element_by_xpath method and specify the xpath expression for the first element in the table.

  • I need to wait for the element to be present wait.until(EC.presence_of_element_located((By.XPATH, "//table//tbody//tr//a[@data-refid='recordId'][0]"))). This particular code [0] is not working – Ben David Jul 04 '23 at 05:23
  • In xpath how to add "//table//tbody//tr//a[@data-refid='recordId'][0]" [0] to expression – Ben David Jul 04 '23 at 05:25
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 05 '23 at 13:07
0

As pointed out before you can use

driver.find_element()

It returns the first found element within DOM tree which fits the xpath.

driver.find_elements() 

returns all elements with specified xpath within DOM tree.

using find_element:

  wait.until(EC.presence_of_element_located((By.XPATH, "//table//tbody//tr//a[@data-refid='recordId']")))
    driver.implicitly_wait(20)
    line_item = driver.find_element("xpath", "//table//tbody//tr//a[@data-refid='recordId']")
    print(line_item)

using find_elements():

 wait.until(EC.presence_of_element_located((By.XPATH, "//table//tbody//tr//a[@data-refid='recordId']")))
    driver.implicitly_wait(20)
    list_of_all_elements = driver.find_elements("xpath", "//table//tbody//tr//a[@data-refid='recordId']")
    line_item = list_of_all_elements[0]
    print(line_item)

This cheatsheet has a good section for locating list/table elements. devhints.io/xpath

Knight
  • 205
  • 1
  • 9
0

To identify the first element in a <table> using an index instead of presence_of_element_located() you need to induce WebDriverWait for the visibility_of_all_elements_located() and you can use the following locator strategies:

  • Line of code:

    line_item = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//table//tbody//tr//a[@data-refid='recordId']")))[0]
    print(line_item[0])
    
  • Note : You have to add the following imports :

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

Reference

You can find a couple of relevant detailed discussions in:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352