Reputation: 963
I am trying to take some scores from websites while using webdriver. I tried so far XPath, CSS, Classname but, sometimes it is located the item, sometimes it does not.
This is the HTML code that I have been trying to take it:
<td class="score" rowspan="6"><span class="p1_home">0</span> - <span class="p1_away">0</span></td>
And this is my code (that i tried so far) :
firstHalf[i] = Driver.FindElement(By.XPath("//*[@id=\"parts\"]/tbody/tr[2]/td[2]")).Text;
Other versions :
firstHalf[i] = Driver.FindElement(By.CssSelector("#parts > tbody > tr:nth-child(2) > td.score")).Text;
firstHalf[i] = Driver.FindElement(By.ClassName("score")).Text;
And also I tried the child classes (under score classes), but the result is same, sometimes can be located the element, sometimes it cannot.
Any suggestion?
Update : To my code, I put some wait
or Thread.Sleep
still will not work.
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();
}
}
}
Upvotes: 0
Views: 977
Reputation: 963
Okay, I found a solution with a different approach. Instead of getting two specific class, I used parent class score
. Also, I deleted the "for loop" and "try" and "catch" which I am using for finding the object again and again.
To my main loop, I added "try" and "catch". When I got the exception, I decreased the loop counter, closed the window and opened again. Also, I added some Thread.Sleep
in order not to get errors because Web-Driver acts so fast this causes a problem.
Updated Version of my Code:
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());
}
}
Upvotes: 0
Reputation: 1657
To locate element of particular class and attribute you can use CSS selector. For example:
Driver.FindElement(By.CssSelector(".score[rowspan='6']")).Text;
In case you having trouble to locate element reliably, you might want get it after certain conditions are met, like so:
WebDriverWait wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(30));
IWebElement element = wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector(".score[rowspan='6']")));
Upvotes: 1
Reputation: 4739
You can use
//span[@class='p1_home']
//span[@class='p1_away']
Upvotes: 1