3

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'.    
}
2
  • And, what is the JavaScript you want read? Can you provide that? Commented Mar 15, 2015 at 16:49
  • it's in the link whoscored.com/Regions/81/Tournaments/3/Germany-Bundesliga var allRegions = [{type:1, id:248, flg:'flg-caf', name: 'Africa', tournaments: [{id:290, url:'/Regions/248/Tournaments/290/Africa-CAF-Champions-League', name:'CAF Champions League'},{id:573, url:'/Regions/248/Tournaments/573/Africa-', name:''},... sorry it's too long to paste here Commented Mar 15, 2015 at 16:57

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

OK. But, what are trying to accomplish here?
thanks for your help. sry, i fell asleep last night :)
@namvo that's ok😬 hope this helped

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.