c# - 如何在 C# Selenium 中获取表数据并将其保存在任何文档中

标签 c# selenium selenium-webdriver

driver.SwitchTo().Frame("menu");
WebDriverWait wait1 = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
wait1.Until(ExpectedConditions.ElementExists(By.CssSelector("a[href='eventLog.cgi?command=0']")));
driver.FindElement(By.CssSelector("a[href='eventLog.cgi?command=0']")).Click();

driver.SwitchTo().Frame("content");
WebDriverWait wait2 = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait2.Until(ExpectedConditions.ElementExists(By.CssSelector("a[href='cgi-bin/terminal.cgi']")));
IWebElement baseTable = driver.FindElement(By.ClassName("TableText1"));
// gets all table rows
ICollection<IWebElement> rows = baseTable.FindElements(By.TagName("tr"));
// for every row
IWebElement matchedRow = null;
foreach (var row in rows)
{
    Console.WriteLine(row.FindElement(By.XPath("td/a")).GetAttribute("href"));
}

首先在.Frame("content")中找不到内容,如果注释了,则在.FromSeconds(10)中超时。如果对此进行注释,则在 .FindElement(By.ClassName("TableText1") 中找不到元素。 html代码在这里

<table class="TableText1" nowrap="">
<tbody><tr>

<tr>
<td class="Table_Header">&nbsp;</td><td class="Table_Header"><a href="eventLog.cgi?command=0">User ID</a></td>
<td class="Table_Header"><a href="eventLog.cgi?command=0">Name</a></td>
<td class="Table_Header"><a href="eventLog.cgi?command=0">Department</a></td>
<td class="Table_Header"><a href="eventLog.cgi?command=0">Date Time<img src="/sort_arrow_down.gif" border="0"></a></td>


<tr nowrap=""><td class="Table_List">1</td><td class="Table_List"> <a href="employee.cgi?action=modify&amp;rid=14">319</a></td><td class="Table_List">Abul Hosain</td><td class="Table_List">General</td><td class="Table_List">2017/01/29 15:22:33</td></tr>
<tr nowrap=""><td class="Table_List_diff">2</td><td class="Table_List_diff"> <a href="employee.cgi?action=modify&amp;rid=49">310</a></td><td class="Table_List_diff">Tabassum Tamanna</td><td class="Table_List_diff">General</td><td class="Table_List_diff">2017/01/29 15:19:50</td></tr>
<tr><td colspan="10"><hr></td></tr>
<tr>
   
</tr></tbody></table>

最佳答案

希望您正在切换正确的框架。如果您的文档中有多个框架,并且您已经切换到第 1 帧,那么您首先需要从第 1 帧切换回来,如下所示 -

driver.SwitchTo().DefaultContent();  

然后切换到另一个框架并执行您的操作

使用以下代码提取表数据 -

IList<IWebElement> allElement = driver.FindElements(By.TagName("td"));
 foreach (IWebElement element in allElement )
 {
    string cellText= element.Text;
    Console.WriteLine(cellText);
 }

关于c# - 如何在 C# Selenium 中获取表数据并将其保存在任何文档中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41919615/

相关文章:

c# - .Net 中的低功耗蓝牙 (C#)

java - 如何在 selenium webdriver 3.0 beta 中使用 geckodriver?

firefox - Selenium in -browserSessionReuse 模式启动一个新的浏览器

python - 如何解决启动 Chrome 时出现 'Getting Default Adapter failed' 错误并尝试使用 Selenium 使用 ChromeDriver 访问网页

java - 无法点击元素 - Selenium WebDriver

c# : Type. 从 exe 类型字符串上的 dll 调用的 GetType

c# - 如何从字符串中提取起始字符?

c# - 无法使用 mdbg 从进程分离

PHPUnit 与 Selenium

java - 是否需要使用 driver.close() 方法?