网页数据抓取怎么写(网页抓取的具体实现功能代码,请大家不吝指教,在此谢过!)
优采云 发布时间: 2022-02-28 10:21网页数据抓取怎么写(网页抓取的具体实现功能代码,请大家不吝指教,在此谢过!)
一直在想整理一下网页抓取的具体实现功能代码,方便大家指正,也方便我自己学习和指正。当然,这并不适用于所有网页。自己写的函数有限,只能用于网页特定结构的数据采集。如果有更好的方法,请不吝赐教。
一、抓取网页内容:
网页爬取的代码很多,网上可以搜索到。以下方法是我找到的一种供参考:
<p>///
/// 获取网页全部源代码
///
/// /要访问的网站地址
/// 目标网页的编码,如果传入的是null或者"",那就自动分析网页的编码
///
public static string getHtml(string url, params string[] charSets)
{
try
{
string charSet = null;
if (charSets.Length == 1)
{
charSet = charSets[0];
}
WebClient myWebClient = new WebClient(); //创建WebClient实例myWebClient
// 需要注意的:
//有的网页可能下不下来,有种种原因比如需要cookie,编码问题等等
//这是就要具体问题具体分析比如在头部加入cookie
// webclient.Headers.Add("Cookie", cookie);
//这样可能需要一些重载方法.根据需要写就可以了
//获取或设置用于对向 Internet 资源的请求进行身份验证的网络凭据.
myWebClient.Credentials = CredentialCache.DefaultCredentials;
//如果服务器要验证用户名,密码
//NetworkCredential mycred = new NetworkCredential(struser, strpassword);
//myWebClient.Credentials = mycred;
//从资源下载数据并返回字节数组.(加@是因为网址中间有"/"符号)
byte[] myDataBuffer = myWebClient.DownloadData(url);
string strWebData = Encoding.Default.GetString(myDataBuffer);
//获取网页字符编码描述信息
Match charSetMatch = Regex.Match(strWebData, "