如何使用Selenium读取javascript变量?
我正在学习使用如何使用Selenium读取javascript变量?,javascript,c#,selenium,selenium-webdriver,webdriver,Javascript,C#,Selenium,Selenium Webdriver,Webdriver,我正在学习使用SeleniumWebDriver(最新版本)阅读javascript变量。有时有效,有时无效。下面是我在whoscored.com上的尝试,它一直显示错误 using (IWebDriver driver = new ChromeDriver()) { driver.Navigate().GoToUrl("http://www.whoscored.com/Regions/81/Tournaments/3/Germany-Bundesliga"
SeleniumWebDriver
(最新版本)阅读javascript
变量。有时有效,有时无效。下面是我在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'.
}
我认为你应该改变
var obj = (object)js.ExecuteScript("return window.allRegions;");
到
打印:
非洲阿尔巴尼亚
阿尔及利亚
…
赞比亚
津巴布韦
那么,您想要阅读的JavaScript是什么?你能提供吗?它在链接var allRegions=[{type:1,id:248,flg:'flg-caf',name:'Africa',tournaments:[{id:290,url:'/Regions/248/tournaments/290/非洲caf冠军联赛',name:'caf冠军联赛',{id:573,url:'/Regions/248/tournaments/573/Africa-',name:'',…对不起,粘贴到这里太长了。好的。但是,你想在这里完成什么?谢谢你的帮助。sry,我昨晚睡着了:)@namvo没关系
List<object> list = js.ExecuteScript("return window.allRegions;") as List<object>;
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);
}