0

我有以下代码可以提取 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);
                }
        }
    }

但是我需要这个更具体。

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

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

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

4

1 回答 1

0

查找具有指定 '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
        //...
    }
}
于 2015-08-02T10:19:06.077 回答