如何使用Selenium读取javascript变量?

时间:2015-03-15 16:46:10

标签: javascript c# selenium selenium-webdriver webdriver

我正在学习使用javascript(最新版本)阅读Selenium WebDriver变量。有时它有效,有时不行。以下是我对 whoscored.com 的尝试,它会一直显示错误

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'.    
}

1 个答案:

答案 0 :(得分:3)

我认为你应该改变

var obj = (object)js.ExecuteScript("return window.allRegions;");

List<object> list = js.ExecuteScript("return window.allRegions;") as List<object>;

因为,return window.allRegions;不会返回string,而是array objects

修改

刚刚浏览了该页面,看起来window.allRegions会返回Listjson个对象。并且,确实感觉创建一个json对象列表可能是不必要的编程压倒性的。我建议您通过修改javascript或执行一些过滤操作来缩小目标范围。

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);
}
  

打印

     

非洲
  阿尔巴尼亚
  阿尔及利亚
  ...
  赞比亚
  津巴布韦