【发布时间】:2015-03-10 20:52:29
【问题描述】:
我有一个具有以下功能的 winform 应用程序:
- 有一个多行文本框,每行包含一个 URL - 大约 30 个 URL(每个 URL 不同但网页相同(只是域不同);
- 我有另一个文本框,我可以在其中编写一个命令和一个按钮,该按钮将该命令发送到来自网页的输入字段。
- 我有一个 WebBrowser 控制器(我想在 一个 控制器中完成所有事情)
该网页由一个文本框和一个按钮组成,我在该文本框中插入命令后希望单击该按钮。
到目前为止我的代码:
//get path for the text file to import the URLs to my textbox to see them
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog fbd1 = new OpenFileDialog();
fbd1.Title = "Open Dictionary(only .txt)";
fbd1.Filter = "TXT files|*.txt";
fbd1.InitialDirectory = @"M:\";
if (fbd1.ShowDialog(this) == DialogResult.OK)
path = fbd1.FileName;
}
//import the content of .txt to my textbox
private void button2_Click(object sender, EventArgs e)
{
textBox1.Lines = File.ReadAllLines(path);
}
//click the button from webpage
private void button3_Click(object sender, EventArgs e)
{
this.webBrowser1.Document.GetElementById("_act").InvokeMember("click");
}
//parse the value of the textbox and press the button from the webpage
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
newValue = textBox2.Text;
HtmlDocument doc = this.webBrowser1.Document;
doc.GetElementById("_cmd").SetAttribute("Value", newValue);
}
现在,我如何将我的文本框中的所有这 30 个 URL 添加到同一个 web 控制器中,以便我可以将相同的命令发送到所有网页的所有文本框,然后按下所有文本框的按钮?
//编辑1 所以,我调整了@Setsu 方法并创建了以下内容:
public IEnumerable<string> GetUrlList()
{
string f = File.ReadAllText(path); ;
List<string> lines = new List<string>();
using (StreamReader r = new StreamReader(f))
{
string line;
while ((line = r.ReadLine()) != null)
lines.Add(line);
}
return lines;
}
现在,这是返回它应该返回的内容,以便解析每个 URL 吗?
【问题讨论】:
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
-
您不能,因为单个 WebBrowser 对象一次只能浏览一个页面。您要么必须同时拥有 30 个 Web 浏览器,要么一次完成一页。请注意,在您的代码中,您永远不会使用您的一个 WebBrowser 导航到任何页面。另请注意,您的
DocumentCompleted事件未正确实现;您需要检查整个页面何时完全完成,因为此事件因框架而多次触发(请参阅此answer)。 -
@Setsu - 所以,我可以通过一次一页做我需要的事情来实现这一点。所以,我将有一个
for(){}循环,它将从文本框中获取每个链接,然后做我需要的,对吧?我在else{}声明之后这样做:if (e.Url.AbsolutePath != (sender as WebBrowser).Url.AbsolutePath) return;? -
@Alexander 我将为您输入更详细的答案。作为旁注,您在那里的代码行可以独立存在而无需 else,因为如果条件为真,则执行将退出事件。这很好,否则您的业务逻辑将被封装在一个巨大的
else语句中。 -
对于您的
GetUrlList实现,您的最后一行只需为return lines;。请注意,每个网址都需要格式正确;即具有必要的协议(例如 http://)。
标签: c# winforms visual-studio