英文:
NoSuchElementException selecting cell value based on header name by xpath
问题
我想选择一个已知行索引的单元格值,并通过标题名称(这里是"Adjusted Amount")来选择它。
我的代码如下:
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')
但仍然出现了"NoSuchElementException"异常。
HTML的快照:
英文:
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:
答案1
得分: 1
以下是翻译好的内容:
- 给定的HTML代码如下:
-
在你的代码行中存在一些问题,你需要按照以下方式解决:
-
包含文本“已调整金额”的元素位于一个
<iframe>
中,因此你需要使用WebDriverWait来等待所需的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")))
-
包含文本“已调整金额”的元素不在任何
<th>
中,而是在<td>
中。因此,要引用<td>
元素,理想情况下,你需要使用WebDriverWait来等待visibility_of_element_located(),并可以使用以下定位策略: -
使用_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)']")))
- 使用_XPATH_:
WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//form[contains(@name, 'TotalBondCalculation')]/table/table/tbody/tr/td[text()='已调整金额']")))
- 注意:你需要添加以下导入语句:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
英文:
Given the 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 desiredframe_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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论