I'm learning to read javascript variable using Selenium WebDriver (latest version). Sometimes it works, sometimes not. Below is my try on whoscored.com and it keeps showing error
using (IWebDriver driver = new ChromeDriver())
{
driver.Navigate().GoToUrl("http://www.whoscored.com/Regions/81/Tournaments/3/Germany-Bundesliga");
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
var tournament = wait.Until(ExpectedConditions.ElementExists(By.Id("tournament-fixture-wrapper")));
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
var obj = (object)js.ExecuteScript("return window.allRegions;"); //always return error 'Additional information: Unable to cast object of type 'System.Int64' to type 'System.String'.
}
I think you should change
var obj = (object)js.ExecuteScript("return window.allRegions;");
to
List<object> list = js.ExecuteScript("return window.allRegions;") as List<object>;
since, return window.allRegions; does not return a string but array of objects.
Edit
Just went through the page and looks like window.allRegions returns a List of json objects. And, does feel like creating a list of json object can be unwanted overwhelming of programming. I suggest you to narrow down the goal either with modifying the javascript or performing some filtering like following.
var wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(30));
var tournament = wait.Until(ExpectedConditions.ElementExists(By.Id("tournament-fixture-wrapper")));
IJavaScriptExecutor js = _driver as IJavaScriptExecutor;
//getting count of regions
long count = (long)js.ExecuteScript("return window.allRegions.length;");
for (int i = 0; i < count; i++)
{
//grab the name of countries if that's what you wanted
string name = js.ExecuteScript("return window.allRegions[" + i + "].name;") as string;
Console.WriteLine(name);
}
Print:
Africa
Albania
Algeria
...
Zambia
Zimbabwe
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With