想要获取表格中出现的行数 Xpath 我传递的是.//*[@id='ctl00_mainContent_Tabs_TabPanelEmploymentAdmin_EmploymentAdmin_grvAssignmentHistory']
我的网页HTML就像
<table id="ctl00_mainContent_Tabs_TabPanelEmploymentAdmin_EmploymentAdmin_grvAssignmentHistory"
<tbody>
<tr>
<th></th>
<th></th>
<th></th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
我的代码在输出时返回0。
IWebElement TargetElement = driver.FindElement(By.XPath(xPathVal));
IList<IWebElement> ElementCollectionHead = TargetElement.FindElements(By.XPath(xPathVal+"/tbody/tr[*]"));
int RowCount = ElementCollectionHead.Count;
答案 0 :(得分:1)
此问题的两个可能原因如下:
iframe
内部,如@Richard所述。第一个问题的解决方案可能是使用显式等待FindElement()
(正如旁注,我希望CssSelector
超过XPath
,因为我不必使用XPath)
By css = By.CssSelector("#ctl00_mainContent_Tabs_TabPanelEmploymentAdmin_EmploymentAdmin_grvAssignmentHistory tr");
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
IList<IWebElement> elementCollectionHead = wait.Until(webDriver => webDriver.FindElements(css));
int rowCount = elementCollectionHead.Count;
如果问题是iframe
,那么您必须使用SwitchTo()
才能切换到iframe
,然后查找元素
// you can use xpath or cssselector to identify the iframe
driver.SwitchTo().Frame(driver.FindElement(By.Id("iframe id")));
By css = By.CssSelector("#ctl00_mainContent_Tabs_TabPanelEmploymentAdmin_EmploymentAdmin_grvAssignmentHistory tr");
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
IList<IWebElement> elementCollectionHead = wait.Until(webDriver => webDriver.FindElements(css));
int rowCount = elementCollectionHead.Count;
driver.SwitchTo().DefaultContent();
答案 1 :(得分:0)
以前我在使用
IWebElement TargetElement = driver.FindElement(By.XPath(xPathVal));
IList<IWebElement> ElementCollectionHead = TargetElement.FindElements(By.XPath(xPathVal+"/tbody/tr[*]"));
int RowCount = ElementCollectionHead.Count;
问题出在第二行。它应该是:
IList<IWebElement> ElementCollectionHead = driver.FindElements(By.XPath(xPathVal + "/tbody/tr[*]"));
不知道为什么1号没有工作。如果有人可以,那么我会感恩。