哪个cms方便快速建站,毕业生登记表自我鉴定模板,网上推广技巧有哪些,商场商城网站建设方案Unity C# 之 Http 获取网页的 html 数据#xff0c;并去掉 html 格式等相关信息 目录
Unity C# 之 Http 获取网页的 html 数据#xff0c;并去掉 html 格式等相关信息
一、简单介绍
二、实现原理
三、注意事项
四、效果预览 五、关键代码 一、简单介绍
Unity中的一些知…Unity C# 之 Http 获取网页的 html 数据并去掉 html 格式等相关信息 目录
Unity C# 之 Http 获取网页的 html 数据并去掉 html 格式等相关信息
一、简单介绍
二、实现原理
三、注意事项
四、效果预览 五、关键代码 一、简单介绍
Unity中的一些知识点整理。
本节简单介绍在Unity开发中的使用 HttpClient获取指定网页的相关信息然后进行数据清洗去掉html 格式以及标签函数多余的空格等信息仅留下和网页显示差不多的文字信息为什么这么做呢其实这里一个使用场景是把网页数据喂给GPT然后让 GPT 进行处理总结如果你有新的方式也可以留言多谢。 二、实现原理
1、HttpClient 获取指定网页的 html 数据
2、使用 HtmlAgilityPack 进行 html 的数据进行 去除所有的script标签及其内容获取纯文本内容最后再去除多余的空格和空行 三、注意事项
1、直接代码访问网页最好添加上 User-Agent不然可能不能正常访问
2、注意 NuGet 安装 HtmlAgilityPack 包 四、效果预览 五、关键代码
using HtmlAgilityPack;
using System;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;namespace TestHtml
{class Program{static async System.Threading.Tasks.Task Main(string[] args){//string url https://movie.douban.com/chart;//string url http://www.weather.com.cn/;//string url https://movie.douban.com/;//string url http://time.tianqi.com/;string url http://time.tianqi.com/shenzhen/;string htmlContent htmlheadtitleSample Page/titlescriptfunction myFunction() {alert(Hello!);}/script/headbodyh1Welcome to My Page/h1pThis is a sample page with some content./p/body/html;using (HttpClient client new HttpClient()){// 设置请求头以模拟浏览器访问client.DefaultRequestHeaders.Add(User-Agent, Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3);// 访问网页并获取HTML内容htmlContent await client.GetStringAsync(url);// 输出获取的HTML内容//Console.WriteLine(htmlContent);}// 创建HtmlDocument对象并加载HTML内容HtmlDocument doc new HtmlDocument();doc.LoadHtml(htmlContent);// 去除所有的script标签及其内容foreach (var script in doc.DocumentNode.DescendantsAndSelf(script).ToArray()){script.Remove();}// 获取纯文本内容string text doc.DocumentNode.InnerText;// 去除多余的空格和空行text Regex.Replace(text, \s, ).Trim();// 输出展示内容Console.WriteLine(text);}}
}