Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read javascript variable using Selenium?

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'.    
}
like image 822
nam vo Avatar asked Aug 10 '26 17:08

nam vo


1 Answers

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

like image 196
Saifur Avatar answered Aug 13 '26 07:08

Saifur