无法找到现有元素

时间:2018-08-09 18:10:18

标签: c# selenium

我正在使用Seleniumthis网站获取数据,遇到了间歇性发生的问题,我认为此问题与网站每x秒刷新一次页面有关。在上面链接的页面上,我试图获取此表:

enter image description here

我的代码具有以下设计:

//Navigate to fixture page.
driver.Navigate().GoToUrl("http://www.oddsportal.com/soccer/europe/europa-league/fc-copenhagen-stjarnan-hzwurDB2/");

//Get all the available categories (eg: 1X2, AH, O/U etc...).
var listItems = driver.FindElement(By.Id("bettype-tabs-scope")).FindElements(By.TagName("li"));

//Get the tab 2nd Half.
var category = listItems.Where(li => li.Text == "2nd Half").SingleOrDefault();

//Click on the tab for load the table.
if (category != null)
{
   category.Click();
}
else
{
   //Tab doesn't exist, return an empty string.
   return string.Empty;
}

//Get the table.
var table = driver.FindElement(By.XPath("(//table[contains(@class, 'table-main')])[1]//tbody//tr[normalize-space()]"));

正如我所说的,此代码有效,但有时会出现此错误:

  

:'没有这样的元素:无法找到元素:{“ method”:“ xpath”,“ selector”:“((// table [contains(@class,'table-main')])){{3} } // tbody // tr [normalize-space()]“}     (会议信息:无头铬= 68.0.3440.84)     (驱动程序信息:chromedriver = 2.40.565498(ea082db3280dd6843ebfb08a625e3eb905c4f5ab),platform = Windows NT 10.0.17134 x86_64)'

我还尝试在点击模拟后添加一个隐式等待:

driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);

但这不能解决问题。

有人知道我该怎么处理吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

您需要在点击2nd Half链接后添加一些明确的等待。因为,表加载需要一些时间。

修改后的代码:

WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(5));
//DotNetSeleniumExtras.WaitHelpers NuGet package needs to be added
wait.Until(ExpectedConditions.ElementIsVisible(By.XPath("(//table[contains(@class, 'table-main')])[1]//tbody//tr[normalize-space()]")));

//Get the table.
var table = _driver.FindElement(By.XPath("(//table[contains(@class, 'table-main')])[1]//tbody//tr[normalize-space()]"));

Console.WriteLine(table.Text);

输出:

 18bet  
-227
+225
+775
89.6%

编辑:

ExpectedConditions已从OpenQA.Selenium.Support.UI中弃用,并新添加到SeleniumExtras.WaitHelpers中。请包括以下NuGet软件包

需要添加NuGet软件包:

DotNetSeleniumExtras.WaitHelpers

OpenQA.Selenium.Support.UISeleniumExtras.WaitHelpers中都将提供预期条件。为了避免冲突,您可以在一个变量中分配新导入的包,并可以访问所需的方法。

因此您可以像这样(using SeleniumWaitHelper = SeleniumExtras.WaitHelpers;)进行导入,并且ExpectedConditions可以通过SeleniumWaitHelper.ExpectedConditions来访问

代码:

WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(5));
//DotNetSeleniumExtras.WaitHelpers NuGet package needs to be added
wait.Until(SeleniumWaitHelper.ExpectedConditions.ElementIsVisible(By.XPath("(//table[contains(@class, 'table-main')])[1]//tbody//tr[normalize-space()]")));

//Get the table.
var table = _driver.FindElement(By.XPath("(//table[contains(@class, 'table-main')])[1]//tbody//tr[normalize-space()]"));

Console.WriteLine(table.Text);
相关问题