【问题标题】:Get the value of an attribute from webbrowser1从 webbrowser1 获取属性的值
【发布时间】:2015-08-02 10:08:56
【问题描述】:

我有以下代码可以提取 Google 搜索结果中的所有 URL:

    private void button1_Click(object sender, EventArgs e)
    {
        HtmlElementCollection a = webBrowser1.Document.GetElementsByTagName("a");
        foreach (HtmlElement b in a)
        {
            string item = b.GetAttribute("href");
            if (item.Contains("url?q=")) 
            {
            listBox1.Items.Add(item);
                }
        }
    }

但是我需要更具体一点。

Google 的 Chrome 元素检查器有这个,我需要访问这个元素中的 URL:

<cite class="_Rm">www.dicksmith.com.au/apple-<b>ipad</b></cite>

类是“_Rm”,它在一个“引用”标签中,我只需要那个 URL。

【问题讨论】:

    标签: c# webbrowser-control getelementsbytagname getattribute


    【解决方案1】:

    查找具有指定 'class' 和 'tag' 值的 html 元素。然后从 InnerHtml 中检索一个 url。

    HtmlElement FindHtmlElement(string tag, Predicate<HtmlElement> predicate)
    {
        try
        {            
            var elements = webBrowser1.Document.GetElementsByTagName(tag);
            foreach (HtmlElement element in elements)
            {
                if (predicate(element))
                {
                    return element;
                }
            }
        }
        catch (Exception ex)
        {
            //Log.Error("Error on finding html element on {0}. Exception: {1}", _webBrowserBot.Url.ToString(), ex.Message);
        }
    
        return null;
    
    }
    
    private void button1_Click(object sender, EventArgs e)
    {
        // search for <cite class="_Rm">www.dicksmith.com.au/apple-<b>ipad</b></cite>
        var element = FindHtmlElement("cite", (h) =>
        {
            return h.GetAttribute("class") == "_Rm";               
        });
    
        string url = "";
        if (element != null)
        {
            // retrieve url only
            int ix = element.InnerHtml.IndexOf("-<b>");
            if (ix > 0)
                url = element.InnerHtml.Remove(ix);
    
            // url obtained
            //...
        }
    }
    

    【讨论】:

    • 您好,我尝试应用上面的代码,它说:// URL OBTAINED,我试图将它输入到listbox1,但它什么也没做,不确定发生了什么。 .. 无论如何感谢您的帮助,非常感谢
    猜你喜欢
    • 2011-10-20
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    • 2021-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多