Search code examples
selenium-webdriverxpathiframecss-selectorswebdriverwait

NoSuchElementException selecting cell value based on header name by xpath


I would like to select a cell value with a known row index and selecting it by header name (here "Adjusted Amount")

My code is as follows:

driver.find_element(By.XPATH, value = f"/html/body/form[2]/table/tbody/tr/td/table/tbody/tr[{2}]/td[th[text()='Adjusted Amount']]/input").get_attribute('value')

but still get a NoSuchElementException.

Snapshot of the HTML:

This is what the page source looks like


Solution

  • Given the HTML:

    html

    There are a couple of issues in your line of code which you need to address as follows:

    • The element with text Adjusted Amount is within an <iframe> so you have to induce WebDriverWait for the desired frame_to_be_available_and_switch_to_it.

       WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe#WorkArea")))
      
    • The element with text Adjusted Amount isn't within any <th> but within <td>. So to reference the <td> element ideally you need to induce WebDriverWait for the visibility_of_element_located() and you can use the following locator strategies:

    • Using CSS_SELECTOR:

      WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "form[name*='TotalBondCalculation table table > tbody > tr td:nth-child(7)']")))
      
    • Using XPATH:

      WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//form[contains(@name, 'TotalBondCalculation')]//table//table/tbody/tr//td[text()='Adjusted Amount']")))
      
    • 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