c#写一个搜索爬虫代码
using System;
using System.Net;
using System.IO;
using HtmlAgilityPack; // 引入网页解析库HtmlAgilityPack
namespace SearchCrawler // 定义命名空间SearchCrawler
{
class Program // 定义类Program
{
static void Main(string[] args) // 程序入口函数,定义Main函数
{
string url = "https://www.baidu.com/"; // 要抓取的url地址(这里为百度首页)
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//创建一个请求对象request
request.Method = "GET";//请求方式为GET
HttpWebResponse response = (HttpWebResponse)request.GetResponse();//获取响应对象response
Stream responseStream = response.GetResponseStream();//从response中获取流数据responseStream
StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.UTF8);//将流数据读入文本流reader中,并使用UTF8格式进行编码处理。
String htmlStr = reader.ReadToEnd();//将文本流中的所有内容保存到字符串htmlStr中。
HtmlDocument doc=new HtmlDocument();//创建HtmlDocument对象doc,用于存储html文件。 doc.LoadHtml(htmlStr);//将htmlStr加载到doc对象中。 var divs=doc .DocumentNode .SelectNodes("/div[@class='head_wrapper']"); //通过xpath表达式来选取div标签,即class='head_wrapper'的所有div标签 if (divs !=null ) { foreach (var div in divs ) { Console .WriteLine ("内容:{0}" ,div .InnerText ); } } Console .ReadKey (); } } }
创作工场
免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。
点击这里>>使用🔥专业版,更聪明、更完整、更原创!