例如,我们通过网络爬虫获取到了一张网页,现在需要分析文件结构,将不必要的信息删除掉,最终,只留下我们自己需要的信息。
思路:读取一个html文件,将其保存成string类型,然后清除掉其中不需要的部分,并进行保存。
步骤分析
- 读取本地文本文件"C:\file.html" (地址根据自己的需求输入)
- 字符串匹配 - 找到对应字符串,根据匹配到的script标签内容,删除所有
<script></script>
代码块 - 用字符串截取的方式 - 删掉
<div class="rw-view cargo-detail-price"></div>
中包含的代码块 (根据需求随机删DIV即可)- 匹配思路: 先找到 对应
class
第一行的<div>
– 然后找到</div>
结尾处 — 截取并删除
- 匹配思路: 先找到 对应
- 同上述方式,删掉其他不必要的代码块 最终只返回自己需要的信息
以下是代码实现
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace day0116文本处理
{
class Program
{
public static string htmlScri = string.Empty;
static void Main(string[] args)
{
//读取一个html文件
string htmlPath = "C:\\Users\\windx\\Desktop\\0113新任务\\HXQ_02\\货品清单.html";
Stream myStream = new FileStream(htmlPath, FileMode.Open);
//使用UTF-8的格式读取html页面
Encoding encode = System.Text.Encoding.GetEncoding("UTF-8");
//用指定的字符编码为指定的流初始化 StreamReader 类的一个新实例
StreamReader myStreamReader = new StreamReader(myStream, encode);
//读取来自流的当前位置到结尾的所有字符 返回一个字符串str
string strhtml = myStreamReader.ReadToEnd();
//通过正则表达式,获取html中<script></script>所包含的内容
string patten = "(<script(.*?)>)(.|\n)*?(</script>)";
string mStr = string.Empty;
MatchCollection mc = Regex.Matches(strhtml, patten);
for (int i = 0; i < mc.Count; i++)
{
//Match m = mc[i];
mStr = mc[i].ToString();
//每匹配到一个就删一个
strhtml = strhtml.Replace(mStr, " ");
htmlScri += mStr + "\r\n"; //这是所有匹配到的<script></script>代码块
}
//Console.Write(strhtml);
//Console.Write(htmlScri);
//Console.ReadKey();
//完成html中script标签的删除
//获取到要截取的<header> -- 索引位置
int indexStart = 0;
int indexEnd = 0;
KeyStartEnd(strhtml, ref indexStart, ref indexEnd);
Console.WriteLine("起始位置:{0}\r\n 结束位置:{1}",indexStart, indexEnd);
//根据索引位置来截取内容
int keyHeadLength = indexEnd - indexStart;
string strHtmlHead = strhtml.Substring(indexStart, keyHeadLength);
strhtml = strhtml.Replace(strHtmlHead, " ");
#region 将改变后的html写入至文件夹
//接下来把strhtml 还原成一个新文件返回到文件夹中去
//重置流的索引 --清空重写
myStream.Seek(0, SeekOrigin.Begin);
myStream.SetLength(0);
//将处理过后的文件写入文件夹,并保存,关闭资源
StreamWriter swhtml = new StreamWriter(myStream, encode); // 在原有的基础上改变
//如果我要保存到一个新的文件中:
//System.IO.File.WriteAllText(@"C:\Users\windx\Desktop\0113新任务\HXQ_02\货品清单_改变后.html", strhtml);
swhtml.Write(strhtml);
swhtml.Flush(); //Flush()方法将所有信息从基础缓冲区移动到其目标或清除缓冲区,或者同时执行这两种操作。
swhtml.Close();
#endregion
myStream.Close();
}
/// <summary>
/// 传入一个html的字符串
/// </summary>
/// <param name="strhtml">完整html的字符串</param>
/// <param name="indexStart">要截取的起始位置</param>
/// <param name="indexEnd">要截取的结束位置</param>
public static void KeyStartEnd(string strhtml,ref int indexStart,ref int indexEnd)
{
//删掉DIV -- <div class="xxxxxx-header"></div> -- 找到<header>的起始位置
string _keyWordHead = "rw-view rw-lst-header container-head";
int index_head = 0; //该字符串出现的索引位置
int count_head = 0; //该字符串一共出现的次数
while ((index_head = strhtml.IndexOf(_keyWordHead, index_head)) != -1)
{
count_head++;
Console.WriteLine("第{0}次;索引是{1}", count_head, index_head);
indexStart = index_head - 12; //获取索引倒数至'_<div>'前即可
index_head = index_head + _keyWordHead.Length;
}
//Console.WriteLine("_keyWordHead 出现的次数:{0} \r\n indexStart: {1}", count_head, indexStart); //一共出现的次数
//找到header_end--</div> 结束位置
string _keyWordEnd = "rw-view content";
int index_headend = 0;
int count_headend = 0;
while ((index_headend = strhtml.IndexOf(_keyWordEnd, index_headend)) != -1)
{
count_headend++;
Console.WriteLine("第{0}次;索引是{1}", count_headend, index_headend);
indexEnd = index_headend - 12;
index_headend = index_headend + _keyWordEnd.Length;
}
//Console.WriteLine("_keyWordEnd 出现的次数:{0} \r\n indexEnd: {1}", count_headend, indexEnd);
}
}
}
在写代码之前,先把完整的思路清理出来,然后再根据思路去找对应的实现所需要的技术。
更新
代码优化:
代码在完成后优化成可通用的代码块,使函数可复用。
优化后:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace day0116文本处理
{
class Program
{
//header
private const string _keyWordHead = "<div class=\"rw-view rw-lst-header container-head\">";
private const string _keyWordHeadEnd = "<div class=\"rw-view content\">";
//wrapper
private const string _keyWordWrapper = "<div class=\"rw-view pc-header-wrapper\">";
private const string _keyWordWrapperEnd = "<div class=\"rw-view scrollView\"";
static void Main(string[] args)
{
//读取一个html文件
string htmlPath = @"C:\Users\windx\Desktop\0113新任务\HXQ_02\进货单.html";
Stream myStream = new FileStream(htmlPath, FileMode.Open);
//使用UTF-8的格式读取html页面
Encoding encode = System.Text.Encoding.GetEncoding("UTF-8");
//用指定的字符编码为指定的流初始化 StreamReader 类的一个新实例
StreamReader myStreamReader = new StreamReader(myStream, encode);
//读取来自流的当前位置到结尾的所有字符 返回一个字符串str
string strhtml = myStreamReader.ReadToEnd();
//Console.Write(strhtml);
#region 正则获取script
//通过正则表达式,获取html中<script></script>所包含的内容
//string patten = "(<script(.*?)>)(.|\n)*?(</script>)";
//string mStr = string.Empty;
//MatchCollection mc = Regex.Matches(strhtml, patten);
//for (int i = 0; i < mc.Count; i++)
//{
// //Match m = mc[i];
// mStr = mc[i].ToString();
// //在这里删,每匹配到一个就删一个
// strhtml = strhtml.Replace(mStr, " ");
// //htmlScri += mStr + "\r\n"; //这是所有匹配到的<script></script>代码块
//}
//Console.Write(strhtml);
//Console.Write(htmlScri);
//Console.ReadKey();
#endregion
#region 删除script标签
string _keyWordScript = "<script";
string _keyWordScriptEnd = "</script>";
int _keyWordEndLength = _keyWordScriptEnd.Length;
strhtml = KeyWordLoopDel(strhtml, _keyWordScript, _keyWordScriptEnd, _keyWordEndLength);
#endregion
#region 截取header
strhtml = KeyWordLoopDel(strhtml, _keyWordHead, _keyWordHeadEnd, 0);
#endregion
#region 截取wrapper
int _keyWrapperEndLength = -6;
strhtml = KeyWordLoopDel(strhtml, _keyWordWrapper, _keyWordWrapperEnd, _keyWrapperEndLength);
#endregion
#region 完成对html文本的操作后,将改变后的html写入至文件夹
//接下来把strhtml 还原成一个新文件返回到文件夹中去
//重置流的索引 --清空重写
myStream.Seek(0, SeekOrigin.Begin);
myStream.SetLength(0);
//将处理过后的文件写入文件夹,并保存,关闭资源
StreamWriter swhtml = new StreamWriter(myStream, encode); // 在原有的基础上改变
//如果我要保存到一个新的文件中:
//System.IO.File.WriteAllText(@"C:\Users\windx\Desktop\0113新任务\HXQ_02\进货单_改变后.html", strhtml);
swhtml.Write(strhtml);
swhtml.Flush();
swhtml.Close();
#endregion
myStream.Close();
}
/// <summary>
/// 将输入的部分按照指定位置循环查找并删除
/// </summary>
/// <param name="strhtml">完整的html</param>
/// <param name="_keyWordScript">每次查询到需要删除的初始位置</param>
/// <param name="_keyWordScriptEnd">每次查询到需要删除的结束位置</param>
/// <param name="_keyWordEndLength">结尾代码的长度</param>
/// <returns></returns>
public static string KeyWordLoopDel(string strhtml, string _keyWord, string _keyWordEnd, int _keyWordEndLength)
{
int indexStart = KeyWordDel(strhtml, _keyWord, 0); //初始位置
int indexEnd = 0;
while (indexStart != -1)
{
indexEnd = KeyWordDel(strhtml, _keyWordEnd, indexStart); //初始位置
strhtml = strhtml.Substring(0, indexStart) + strhtml.Substring(indexEnd + _keyWordEndLength); //字符串的前后拼接
indexStart = KeyWordDel(strhtml, _keyWord, indexStart);
}
return strhtml;
}
/// <summary>
/// 返回指定字符串的起始位置
/// </summary>
/// <param name="strhtml">完整的html</param>
/// <param name="keyWord">指定字符串</param>
/// <param name="indexStart">起始位置</param>
/// <returns>返回指定字符串的起始位置</returns>
public static int KeyWordDel(string strhtml, string _keyWord, int indexStart)
{
//匹配查询需要查询的string IndexOf-->没查找到则为-1
int index_script = -1;
indexStart = index_script = strhtml.IndexOf(_keyWord, 0); //如果查询到了位置,则返回;如果未能查询到位置,则默认为-1
return indexStart; //返回查询字符串的起始位置
}
}
}
希望该文章能够对大家有所帮助,同时如果文章中有错误或不足之处,还请大家海涵。好好学习,与君共勉。