如何使用 Selenium 读取 javascript 变量?

How to read javascript variable using Selenium?

我正在学习使用 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'.    
}

我觉得你应该改变

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

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

因为,return window.allRegions; 不是 return string,而是 objectsarray

编辑

刚刚浏览了该页面,看起来 window.allRegions return 是 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);
}

Print:

Africa
Albania
Algeria
...
Zambia
Zimbabwe