网页抓取qq(写了一个从网页中抓取信息(如最新的头条新闻))

优采云 发布时间: 2021-10-20 03:07

  网页抓取qq(写了一个从网页中抓取信息(如最新的头条新闻))

  我写了一个类,用于从网页中抓取信息(例如最新的头条新闻、新闻来源、头条新闻、内容等)。本文将介绍如何使用该类抓取网页中需要的信息。本文将以博客园首页的博客标题和链接为例:

  

  上图为博客园首页的DOM树。显然,你只需要提取class为post_item的div,然后提取class为titlelnk的a标记。这样的功能可以通过以下功能来实现:

  ///

/// 在文本html的文本查找标志名为tagName,并且属性attrName的值为attrValue的所有标志

/// 例如:FindTagByAttr(html, "div", "class", "demo")

/// 返回所有class为demo的div标志

/// 前端学习交流QQ群:461593224

///

public static List FindTagByAttr(String html, String tagName, String attrName, String attrValue)

{

String format = String.Format(@"", tagName, attrName, attrValue);

return FindTag(html, tagName, format);

}

public static List FindTag(String html, String name, String format)

{

Regex reg = new Regex(format, RegexOptions.IgnoreCase);

Regex tagReg = new Regex(String.Format(@"", name), RegexOptions.IgnoreCase);

List tags = new List();

int start = 0;

while (true)

{

Match match = reg.Match(html, start);

if (match.Success)

{

start = match.Index + match.Length;

Match tagMatch = null;

int beginTagCount = 1;

while (true)

{

tagMatch = tagReg.Match(html, start);

if (!tagMatch.Success)

{

tagMatch = null;

break;

}

start = tagMatch.Index + tagMatch.Length;

if (tagMatch.Groups[1].Value == "/") beginTagCount--;

else beginTagCount++;

if (beginTagCount == 0) break;

}

if (tagMatch != null)

{

HtmlTag tag = new HtmlTag(name, match.Value, html.Substring(match.Index + match.Length, tagMatch.Index - match.Index - match.Length));

tags.Add(tag);

}

else

{

break;

}

}

else

{

break;

}

}

return tags;

}

  通过上述功能,您可以提取所需的 HTML 标签。要实现爬取,还需要一个下载网页的功能:

  public static String GetHtml(string url)

{

try

{

HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;

req.Timeout = 30 * 1000;

HttpWebResponse response = req.GetResponse() as HttpWebResponse;

Stream stream = response.GetResponseStream();

MemoryStream buffer = new MemoryStream();

Byte[] temp = new Byte[4096];

int count = 0;

while ((count = stream.Read(temp, 0, 4096)) > 0)

{

buffer.Write(temp, 0, count);

}

return Encoding.GetEncoding(response.CharacterSet).GetString(buffer.GetBuffer());

}

catch

{

return String.Empty;

}

}

  /// 前端学习交流QQ群:461593224

  下面以博客园首页的文章标题和链接为例,介绍如何使用HtmlTag类抓取网页信息:

  操作结果如下:

  

  欢迎正在学习前端的同学一起学习

  前端学习交流QQ群:461593224

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线