【发布时间】:2018-12-23 02:17:20
【问题描述】:
我正在尝试使用 WebBrowser 类复制网站的文本(从用户那里获取 URL),但似乎没有任何线程正在运行。我也尝试在没有线程的情况下使用WebBrowser,但它没有用。欢迎任何建议。这是我第一次使用这些库,非常感谢你帮助我得到我想要的东西。
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Windows.Forms;
using System.Threading;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private void runBrowserThread(Uri url)
{
var th = new Thread(() => {
var br = new WebBrowser();
br.DocumentCompleted += browser_DocumentCompleted;
br.Navigate(url);
global::System.Windows.Forms.Application.Run();
object n = new object();
br.Document.ExecCommand("SelectAll",true,n);
br.Document.ExecCommand("Copy",true,n);
string text = Clipboard.GetText();
MessageBox.Show(text, "Text");
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
}
void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var br = sender as WebBrowser;
if (br.Url == e.Url)
{
Console.WriteLine("Natigated to {0}", e.Url);
// global::System.Windows.Forms.Application.ExitThread(); // Stops the thread
}
}
public void url_input_Click(Object sender, EventArgs e)
{
string StringFromTheInput = TextBox1.Text;
System.Uri uri = new System.Uri(StringFromTheInput);
runBrowserThread(uri);
}
public static Dictionary<string, int> WordCount(string content, int numWords = int.MaxValue)
{
var delimiterChars = new char[] { ' ', ',', ':', '\t', '\"', '\r', '{', '}', '[', ']', '=', '/' };
return content
.Split(delimiterChars)
.Where(x => x.Length > 0)
.Select(x => x.ToLower())
.GroupBy(x => x)
.Select(x => new { Word = x.Key, Count = x.Count() })
.OrderByDescending(x => x.Count)
.Take(numWords)
.ToDictionary(x => x.Word, x => x.Count);
}
}
【问题讨论】:
-
br.Navigate(url);之后的任何逻辑都应该在事件处理程序中。 -
@Crowcoder 你是什么意思?谢谢
-
我将尝试详细说明..
br.Navigate(url)之后访问文档的任何代码(如ExecCommand)都应该在browser_DocumentCompleted方法中,因为您无法对文档执行任何操作直到它被加载。 -
@Crowcoder 谢谢,我修好了。但是
browser_DocumentCompleted之后的行根本没有运行。为什么? -
我不知道,但通常你会引用你放在表单上的 Web 浏览器控件,而不是创建一个新控件。