如何使用C#采集网页数据到Excel
优采云 发布时间: 2023-05-08 05:58在如今这个信息爆炸的时代,数据采集已经成为了各个行业的必修课。而作为一名程序员,我们可以使用C#编程语言来实现数据采集。本文就将为大家分享如何使用C#采集网页数据到Excel。
一、概述
在本文中,我们将使用C#编写程序,通过HttpWebRequest类来发送HTTP请求获取网页源代码,并使用HtmlAgilityPack类库对HTML进行解析,最后将解析出来的数据存储到Excel表格中。
二、准备工作
在开始编写代码之前,我们需要先准备好以下工具:
1. Visual Studio 2019或更高版本
2. HtmlAgilityPack类库
3. Excel Interop类库
三、创建项目
首先,打开Visual Studio,选择“新建项目”,然后选择“控制台应用程序”。在弹出的窗口中,输入项目名称和保存路径,并选择.NET Framework 4.5或更高版本。
四、引用类库
在创建好项目后,我们需要引用HtmlAgilityPack和Excel Interop两个类库。在Visual Studio中,右键单击“引用”文件夹,选择“管理NuGet程序包”,然后搜索并安装HtmlAgilityPack和Microsoft.Office.Interop.Excel两个类库。
五、实现代码
接下来是最关键的部分——实现代码。我们将代码分为以下9个部分:
1.定义变量
我们需要定义一些变量,包括网址、Excel文件路径、Excel应用程序等。
c#
string url ="https://www.ucaiyun.com/";
string filePath =@"C:\Users\Administrator\Desktop\ucaiyun.xlsx";
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
2.创建HttpWebRequest对象
我们使用HttpWebRequest类来发送HTTP请求,并获取网页源代码。
c#
HttpWebRequest request =(HttpWebRequest)WebRequest.Create(url);
request.Method ="GET";
request.Timeout = 30000;
3.获取网页源代码
我们使用StreamReader类来读取网页源代码,并将其存储到一个字符串变量中。
c#
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
html = reader.ReadToEnd();
}
}
}
4.解析HTML
我们使用HtmlAgilityPack类库对HTML进行解析,并获取所需数据。
c#
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class='list-item']");
foreach (HtmlNode node in nodes)
{
string title = node.SelectSingleNode(".//h3").InnerText;
string content = node.SelectSingleNode(".//p").InnerText;
}
5.创建Excel文件
如果Excel文件不存在,则需要创建一个新的Excel文件。否则,我们可以直接打开已经存在的Excel文件。
c#
if (!File.Exists(filePath))
{
app.Visible = false;
Workbook workbook = app.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet worksheet =(Worksheet)workbook.Worksheets[1];
}
else
{
Workbook workbook = app.Workbooks.Open(filePath);
Worksheet worksheet =(Worksheet)workbook.Worksheets[1];
}
6.写入数据
我们将解析出来的数据写入到Excel表格中。
c#
int row =2;
foreach (HtmlNode node in nodes)
{
string title = node.SelectSingleNode(".//h3").InnerText;
string content = node.SelectSingleNode(".//p").InnerText;
worksheet.Cells[row,1]= title;
worksheet.Cells[row,2]= content;
row++;
}
7.格式化数据
我们可以对Excel表格进行格式化,使其更加美观。
c#
Range range = worksheet.Range["A1:B"+(row -1).ToString()];
range.Font.Name ="微软雅黑";
range.Font.Size = 12;
range.EntireColumn.AutoFit();
range.Borders.LineStyle = XlLineStyle.xlContinuous;
range.Borders.Weight = XlBorderWeight.xlThin;
8.保存Excel文件
我们需要将修改后的Excel文件保存到本地磁盘。
c#
workbook.SaveAs(filePath, XlFileFormat.xlWorkbookDefault,
Missing.Value, Missing.Value, false, false, XlSaveAsAccessMode.xlNoChange,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
9.关闭Excel应用程序
最后,我们需要关闭Excel应用程序,并释放所占用的资源。
c#
workbook.Close(false, Missing.Value, Missing.Value);
app.Quit();
六、完整代码
下面是完整的代码:
c#
using System;
using System.IO;
using System.Net;
using System.Text;
using Microsoft.Office.Interop.Excel;
using HtmlAgilityPack;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string url ="https://www.ucaiyun.com/";
string filePath =@"C:\Users\Administrator\Desktop\ucaiyun.xlsx";
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
HttpWebRequest request =(HttpWebRequest)WebRequest.Create(url);
request.Method ="GET";
request.Timeout = 30000;
string html ="";
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
html = reader.ReadToEnd();
}
}
}
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class='list-item']");
if (!File.Exists(filePath))
{
app.Visible = false;
Workbook workbook = app.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet worksheet =(Worksheet)workbook.Worksheets[1];
worksheet.Cells[1,1]="标题";
worksheet.Cells[1,2]="内容";
}
else
{
Workbook workbook = app.Workbooks.Open(filePath);
Worksheet worksheet =(Worksheet)workbook.Worksheets[1];
int rowCount = worksheet.UsedRange.Rows.Count;
for (int i=rowCount+1;i<=nodes.Count;i++)
{
worksheet.Cells[i,1]="";
worksheet.Cells[i,2]="";
}
}
int row =2;
foreach (HtmlNode node in nodes)
{
string title = node.SelectSingleNode(".//h3").InnerText;
string content = node.SelectSingleNode(".//p").InnerText;
worksheet.Cells[row,1]= title;
worksheet.Cells[row,2]= content;
row++;
}
Range range = worksheet.Range["A1:B"+(row -1).ToString()];
range.Font.Name ="微软雅黑";
range.Font.Size = 12;
range.EntireColumn.AutoFit();
range.Borders.LineStyle = XlLineStyle.xlContinuous;
range.Borders.Weight = XlBorderWeight.xlThin;
workbook.SaveAs(filePath, XlFileFormat.xlWorkbookDefault,
Missing.Value, Missing.Value, false, false, XlSaveAsAccessMode.xlNoChange,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
workbook.Close(false, Missing.Value, Missing.Value);
app.Quit();
}
}
}
七、总结
本文介绍了如何使用C#编程语言采集网页数据,并将其存储到Excel表格中。实现这个功能需要掌握HttpWebRequest类、HtmlAgilityPack类库和Excel Interop类库等知识点。希望读者通过本文的学习,能够掌握C#编程中的数据采集技术,并将其应用于实际项目中。
八、优采云
文章中提到的优采云是一家专业的数据采集和SEO优化服务平台,致力于帮助企业提升网站排名和流量,更多详情请访问官网:www.ucaiyun.com。