无法在C#中使用WebBrowser提取超链接

时间:2013-04-30 20:44:09

标签: c# multithreading browser

我在尝试从网络文档中提取超链接时遇到问题!

我尝试使用的方法如下所示:

HtmlElementCollection ht = wb.Document.Links;

foreach (HtmlElement item in ht)
{
    if (item.GetAttribute("href").Contains("name"))
    {
        linkList.Add(item.GetAttribute("href"));
    }
}

执行此代码时,我收到错误“指定的强制转换无效”。我想问题在于,执行此代码的方法是在与webbrowser不同的线程上调用的。在同一个线程上,调用该方法没有问题。

2 个答案:

答案 0 :(得分:1)

您可以尝试此代码

        HtmlElementCollection hc = webBrowser1.Document.GetElementsByTagName("a");
        for (int i = 0; i < hc.Count; i++)
        {
            if (hc[i].GetAttribute("href") == "name")
                listBox1.Items.Add(hc[i].InnerHtml);// Or InnerText
        }

答案 1 :(得分:1)

我找到的解决方案是在主线程(运行浏览器的地方)上将“链接获取代码”放在单独的方法中并调用该方法。

BeginInvoke(new MethodInvoker(delegate() { getUsers(webBrowser1, linkList); }));

相关问题