此question的延续,其中jQuery片段在浏览器中工作,但是当我尝试将脚本的返回值获取到C#中的列表中时,它看起来是null。我试图从内部网页获得listYears的年份,例如:2018、2017、2015、2012。在浏览器上运行jQuery可以正确地提取年份,但是当我尝试使用C#将jQuery返回的年份放入列表时,它似乎没有填充,或者我没有使用正确的C#构造。我在C#代码中犯了什么错误?
List<string> listYears = new List<string>();
listYears = (List<string>)window.ExecuteScript(@"$(document).ready(function(){
var scr = document.createElement('script');
scr.src = 'https://code.jquery.com/jquery-3.3.1.js';
document.body.appendChild(scr);
var years = []
var thisYear = 0;
$('time').each(function(){
thisYear = parseInt($(this).attr('datetime').split('-')[0]);
years.push(thisYear);
});
return years.toString();
});");
System.Diagnostics.Debug.WriteLine("*************************");
System.Diagnostics.Debug.WriteLine("*************************");
System.Diagnostics.Debug.WriteLine("*************************");
System.Diagnostics.Debug.WriteLine("listYears: " + listYears[0]);
System.Diagnostics.Debug.WriteLine("*************************");
System.Diagnostics.Debug.WriteLine("*************************");
System.Diagnostics.Debug.WriteLine("*************************");
或
System.Diagnostics.Debug.WriteLine("*************************");
System.Diagnostics.Debug.WriteLine("*************************");
System.Diagnostics.Debug.WriteLine("*************************");
System.Diagnostics.Debug.WriteLine("listYears: " + listYears);
System.Diagnostics.Debug.WriteLine("*************************");
System.Diagnostics.Debug.WriteLine("*************************");
System.Diagnostics.Debug.WriteLine("*************************");
答案 0 :(得分:0)
经过反复试验,更正了该问题,listYears现在显示了执行jQuery脚本的所有年份。
var listYears = window.ExecuteScript(@"
$=jQuery;
var years = [];
var thisYear = 0;
$('time').each(function(){
thisYear = parseInt($(this).attr('datetime').split('-')[0]);
// do something with thisYear...
years.push(thisYear);
});
// Write all years to console window.
return years.toString();
");
System.Diagnostics.Debug.WriteLine("*************************");
System.Diagnostics.Debug.WriteLine("*************************");
System.Diagnostics.Debug.WriteLine("*************************");
System.Diagnostics.Debug.WriteLine("listYears: " + listYears);
System.Diagnostics.Debug.WriteLine("*************************");
System.Diagnostics.Debug.WriteLine("*************************");
System.Diagnostics.Debug.WriteLine("*************************");