C#如何使用正規表示式抓取網站資訊的程式碼案例
c#
正規表示式
這篇文章主要介紹了C#使用正規表達式抓取網站資訊,結合實例形式分析了C#針對網頁資訊的正則抓取操作相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了C#使用正規表示式抓取網站資訊的方法。 ##1、建立JdRobber.cs程式類別
public class JdRobber { /// <summary> /// 判断是否京东链接 /// </summary> /// <param name="param"></param> /// <returns></returns> public bool ValidationUrl(string url) { bool result = false; if (!String.IsNullOrEmpty(url)) { Regex regex = new Regex(@"^http://item.jd.com/\d+.html$"); Match match = regex.Match(url); if (match.Success) { result = true; } } return result; } /// <summary> /// 抓取京东信息 /// </summary> /// <param name="param"></param> /// <returns></returns> public void GetInfo(string url) { if (ValidationUrl(url)) { string htmlStr = WebHandler.GetHtmlStr(url, "Default"); if (!String.IsNullOrEmpty(htmlStr)) { string pattern = ""; //正则表达式 string sourceWebID = ""; //商品关键ID string title = ""; //标题 decimal price = 0; //价格 string picName = ""; //图片 //提取商品关键ID pattern = @"http://item.jd.com/(?<Object>\d+).html"; sourceWebID = WebHandler.GetRegexText(url, pattern); //提取标题 pattern = @"<p.*id=\""name\"".*>[\s\S]*<h1>(?<Object>.*?)</h1>"; title = WebHandler.GetRegexText(htmlStr, pattern); //提取图片 int begin = htmlStr.IndexOf("<p id=\"spec-n1\""); int end = htmlStr.IndexOf("</p>", begin + 1); if (begin > 0 && end > 0) { string subPicHtml = htmlStr.Substring(begin, end - begin); pattern = @"<img.*src=\""(?<Object>.*?)\"".*/>"; picName = WebHandler.GetRegexText(subPicHtml, pattern); } //提取价格 if (sourceWebID != "") { string priceUrl = @"http://p.3.cn/prices/get?skuid=J_" + sourceWebID + "&type=1"; string priceJson = WebHandler.GetHtmlStr(priceUrl, "Default"); pattern = @"\""p\"":\""(?<Object>\d+(\.\d{1,2})?)\"""; price = WebHandler.GetValidPrice(WebHandler.GetRegexText(priceJson, pattern)); } Console.WriteLine("商品名称:{0}", title); Console.WriteLine("图片:{0}", picName); Console.WriteLine("价格:{0}", price); } } } }
登入後複製
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
刺客信條陰影:貝殼謎語解決方案
2 週前
By DDD
R.E.P.O.如果您聽不到任何人,如何修復音頻
4 週前
By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
1 個月前
By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

熱門話題

使用 C# 的 Active Directory 指南。在這裡,我們討論 Active Directory 在 C# 中的介紹和工作原理以及語法和範例。

多線程和異步的區別在於,多線程同時執行多個線程,而異步在不阻塞當前線程的情況下執行操作。多線程用於計算密集型任務,而異步用於用戶交互操作。多線程的優勢是提高計算性能,異步的優勢是不阻塞 UI 線程。選擇多線程還是異步取決於任務性質:計算密集型任務使用多線程,與外部資源交互且需要保持 UI 響應的任務使用異步。
