【问题标题】:How to read javascript variable using Selenium?如何使用 Selenium 读取 javascript 变量?
【发布时间】:2015-05-17 18:29:30
【问题描述】:

我正在学习使用Selenium WebDriver(最新版本)读取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'.    
}

【问题讨论】:

  • 还有,你想读的 JavaScript 是什么?你能提供吗?
  • 它在链接中whoscored.com/Regions/81/Tournaments/3/Germany-Bundesliga var allRegions = [{type:1, id:248, flg:'flg-caf', name: 'Africa', 锦标赛: [{id:290, url:'/Regions/248/Tournaments/290/Africa-CAF-Champions-League', name:'CAF Champions League'},{id:573, url:'/Regions/248/Tournaments/573/Africa-' , name:''},...抱歉,这里粘贴太长了

标签: javascript c# selenium selenium-webdriver webdriver


【解决方案1】:

我认为你应该改变

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

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

因为,return window.allRegions; 不返回 string,而是返回 arrayobjects

编辑

刚刚浏览了页面,看起来 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);
}

打印:

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

【讨论】:

  • 好的。但是,这里想要完成什么?
  • 感谢您的帮助。对不起,我昨晚睡着了:)
  • @namvo 没关系?希望这有帮助
猜你喜欢
  • 2012-12-09
  • 2012-10-17
  • 1970-01-01
  • 2020-06-14
  • 1970-01-01
  • 2014-02-14
  • 1970-01-01
  • 1970-01-01
  • 2010-11-28
相关资源
最近更新 更多