将javascript变量中的文本保存到.txt文件中



我正在尝试这段代码,但无法使其工作,它说"名称";文本";不存在于当前上下文中";

CurBrowser.GetMainFrame().ExecuteJavaScriptAsync("for(var i = 0; i < elems1.length; i++){ var textt = elems1[i].innerText}");
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true))
{
outputFile.WriteLine(textt);
}

如何使变量";textt";可到达的

这是一个完整的代码:

private void button3_Click(object sender, EventArgs e)
{
CurBrowser.GetMainFrame().ExecuteJavaScriptAsync("var elems1 = document.getElementsByClassName('question-text')");
CurBrowser.GetMainFrame().ExecuteJavaScriptAsync("for(var i = 0; i < elems1.length; i++){var textt = elems1[i].innerText}");

string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true))
{
outputFile.WriteLine(textt);
}
}

您可能正在寻找ContinueWith(),它可以链接在ExecuteJavaScriptAsync()之后。

在本例中,您需要将JavaScript代码用作返回任何内容的函数(例如textt(。所以我创建了这样的东西:

var myScript = @"(function () {
var textt = "";
var elems1 = document.getElementsByClassName('question-text');
for(var i = 0; i < elems1.length; i++){
textt += elems1[i].innerText
}
return textt;
})();";

然后我异步评估它,并捕获我从该函数返回的结果:

var result = await CurBrowser
.GetMainFrame()
.EvaluateScriptAsync(myScript)
.ContinueWith(t => {
var result = t.Result; // your textt
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true)) {
outputFile.WriteLine(result);
}
});

这只是一个如何运作的建议。

相关内容

  • 没有找到相关文章

最新更新