如何使用 C# 在 webdriver 2 中使用 xpath 获取 webtable 中的确切行数

How to get the exact number of rows in webtable using xpath in webdriver 2 using C#

想要获取 table 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;

造成此问题的两个可能原因如下:

  1. Selenium 需要一些时间来识别元素(元素加载时间)
  2. 如@Richard 所述,元素在 iframe 内。

第一个问题的解决方案可能是使用显式等待 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();

之前我用的是

IWebElement TargetElement = driver.FindElement(By.XPath(xPathVal));
IList<IWebElement> ElementCollectionHead = TargetElement.FindElements(By.XPath(xPathVal+"/tbody/tr[*]"));        
int RowCount = ElementCollectionHead.Count; 

第二个问题 line.It 应该是这样的:

IList<IWebElement> ElementCollectionHead = driver.FindElements(By.XPath(xPathVal + "/tbody/tr[*]"));

不知道为什么 1st 不是 working.If 有人可以然后我将不胜感激。