[英]Save text from javascript variable to .txt file
I am trying this code, but can't get it to work, it says "The name "text" does not exist in the current context"我正在尝试此代码,但无法使其正常工作,它显示“当前上下文中不存在名称“文本””
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);
}
How can I make variable "textt" accessible?如何使变量“textt”可访问?
Here is a full code:这是一个完整的代码:
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);
}
}
You might be looking for ContinueWith()
which can be chained after ExecuteJavaScriptAsync()
.您可能正在寻找可以在ExecuteJavaScriptAsync()
之后链接的ContinueWith()
ExecuteJavaScriptAsync()
。
In this example you need to use your JavaScript code as a function which returns anything (ex. textt).在此示例中,您需要将 JavaScript 代码用作返回任何内容的函数(例如 textt)。 So I've created something like this:所以我创建了这样的东西:
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;
})();";
than I asynchronously evaluate it and catch the result which I am returning from that function:比我异步评估它并捕获我从该函数返回的结果:
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);
}
});
this is just a suggestion of how it might work.这只是它可能如何工作的建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.