[英]Selenium WebDriver - Unable to locate element exception
我正在嘗試使用webdriver從網站上獲得一些分數。 到目前為止,我嘗試過XPath,CSS,Classname,但是有時它位於該項目中,有時卻不在。
這是我一直在嘗試的HTML代碼:
<td class="score" rowspan="6"><span class="p1_home">0</span> - <span class="p1_away">0</span></td>
這是我的代碼(到目前為止我嘗試過):
firstHalf[i] = Driver.FindElement(By.XPath("//*[@id=\"parts\"]/tbody/tr[2]/td[2]")).Text;
其他版本:
firstHalf[i] = Driver.FindElement(By.CssSelector("#parts > tbody > tr:nth-child(2) > td.score")).Text;
firstHalf[i] = Driver.FindElement(By.ClassName("score")).Text;
我也嘗試了子類(在分數類下),但結果是相同的,有時可以找到元素,有時則不能。
有什么建議嗎?
更新:對我的代碼,我wait
或Thread.Sleep
仍然無法正常工作。
for (int r = 0; r < 10; r++)
{
try
{
string d1 = Driver.FindElement(By.XPath("//span[@class='p1_home']")).Text;
string d2 = Driver.FindElement(By.XPath("//span[@class='p1_away']")).Text;
//firstHalf[i] = firstHalf[i].Replace(" ", "");
firstHalf[i] = d1 + "-" + d2;
break;
}
catch (Exception e)
{
Thread.Sleep(300);
r -= 1;
eventCounter++;
if (eventCounter == 10)
{
errorMsg.sendErrMsg(e);
//errorMsg.stopProgram();
}
}
}
您可以使用
//span[@class='p1_home']
//span[@class='p1_away']
要查找特定類和屬性的元素,可以使用CSS選擇器。 例如:
Driver.FindElement(By.CssSelector(".score[rowspan='6']")).Text;
如果您無法可靠地定位元素,則可能需要在滿足某些條件后才能獲取它,例如:
WebDriverWait wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(30));
IWebElement element = wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector(".score[rowspan='6']")));
好的,我找到了另一種方法的解決方案。 我沒有獲得兩個特定的班級,而是使用了父班級score
。 另外,我刪除了用於反復查找對象的“ for循環” , “ try”和“ catch” 。
在我的主循環中,添加了“ try”和“ catch” 。 收到異常后,我減少了循環計數器,關閉了窗口,然后再次打開。 另外,我添加了一些Thread.Sleep
以便不會出錯,因為Web-Driver動作如此之快會導致問題。
我的代碼的更新版本:
for (int i = 0;; i < stopLimit.Count; i++)
{
try
{
Thread.Sleep(500);
string score = Driver.FindElementByCssSelector("#parts > tbody >
tr:nth-child(2) > td.score").Text;
firstHalf[i] = score.Replace(" ", "");
}
catch(Exception)
{
i--;
Thread.Sleep(1500);
Driver.SwitchTo().Window(Driver.WindowHandles.Last());
Driver.Close();
Driver.SwitchTo().Window(Driver.WindowHandles.First());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.