版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、怎樣使用C# 獲取百度搜索結(jié)果,并且解析到目標(biāo)網(wǎng)址我們首先應(yīng)該分析百度的搜索結(jié)果,發(fā)現(xiàn)百度的搜索結(jié)果的格式為:圖中標(biāo)記部分可以知道,百度的搜索結(jié)果都是在id=”content_left”的結(jié)果中的,每個(gè)搜索項(xiàng)目的是以class=”result c-container”作為一項(xiàng), 每項(xiàng)中的題目又是包含在h3標(biāo)簽中,如下圖所示:因此我們有了思路:1. 根據(jù)關(guān)鍵字獲取到百度搜索結(jié)果的整個(gè)HTML文本2. 正則匹配到搜索結(jié)果容器的HTML3. 正則匹配到搜索結(jié)果每一項(xiàng)的HTML4. 取出每項(xiàng)結(jié)果中的題目和鏈接地址直接來(lái)干的,看下面的代碼:using System; using System.Colle
2、ctions.Generic; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Net;using System.IO;namespace BaiduSearchTest struct BaiduEntry public string title, brief, link; class Program static string GetHtml(string keyword) string url = " string encodedKeyword = Ht
3、tpUtility.UrlEncode(keyword, Encoding.GetEncoding(936); /百度使用codepage 936字符編碼來(lái)作為查詢串,果然專注于中文搜索 /更不用說(shuō),還很喜歡微軟 /谷歌能正確識(shí)別UTF-8編碼和codepage這兩種情況,不過(guò)本身網(wǎng)頁(yè)在HTTP頭里標(biāo)明是UTF-8的 /估計(jì)谷歌也不討厭微軟(以及微軟的專有規(guī)范) string query = "s?wd=" + encodedKeyword; HttpWebRequest req; HttpWebResponse response; Stream stream;
4、 req = (HttpWebRequest)WebRequest.Create(url + query); response = (HttpWebResponse)req.GetResponse(); stream = response.GetResponseStream(); int count = 0; byte buf = new byte8192; string decodedString = null; StringBuilder sb = new StringBuilder(); try Console.WriteLine("正在讀取網(wǎng)頁(yè)0的內(nèi)容", url
5、+ query); do count = stream.Read(buf, 0, buf.Length); if (count > 0) decodedString = Encoding.GetEncoding("utf-8").GetString(buf, 0, count); sb.Append(decodedString); while (count > 0); catch Console.WriteLine("網(wǎng)絡(luò)連接失敗,請(qǐng)檢查網(wǎng)絡(luò)設(shè)置。"); return sb.ToString(); static void PrintResul
6、t(List<BaiduEntry> entries) int count = 0; entries.ForEach(delegate(BaiduEntry entry) Console.WriteLine("找到了百度的第0條搜索結(jié)果:", count += 1); if (entry.link != null) Console.WriteLine("找到了一條鏈接:"); Console.WriteLine(entry.link); if (entry.title != null) Console.WriteLine("標(biāo)題為:
7、"); Console.WriteLine(entry.title); if (entry.brief != null) Console.WriteLine("下面是摘要:"); Console.WriteLine(entry.brief); Program.Cut(); ); static void simpleOutput() string html = "<table><tr><td><font>test</font><a>hello</a><br>&l
8、t;/td></tr></table>" Console.WriteLine(RemoveSomeTags(html); static string RemoveVoidTag(string html) string filter = "<br>" ; foreach (string tag in filter) html = html.Replace(tag, ""); return html; static string ReleaseXmlTags(string html) string filt
9、er = "<a.*?>", "</a>", "<em>", "</em>", "<b>", "</b>", "<font.*?>", "</font>" ; foreach (string tag in filter) html = Regex.Replace(html, tag, ""); return html; &
10、#160; static string RemoveSomeTags(string html) html = RemoveVoidTag(html); html = ReleaseXmlTags(html); return html; static void Cut() Console.WriteLine(""); static void MainProc(string input) MainProc(input, false); static void MainProc(string input, bool tagsForBrief) Regex r = n
11、ew Regex("<h3sS*?</h3>", RegexOptions.IgnoreCase); MatchCollection matchCollection = r.Matches(input); List<string> collection = new List<string>(); foreach(Match m in matchCollection) string textReg = "<as*>*>(sS+?)</a>"
12、0; MatchCollection textMatchCollection = Regex.Matches(m.Value, textReg, RegexOptions.IgnoreCase); foreach (Match match in textMatchCollection) if (match.Success) Console.Write(match.Result("$1"); string LinkReg = "http:/(w-+.)+w-+(/w- ./?%&=*)?" MatchColle
13、ction linkMatchCollection = Regex.Matches(m.Value, LinkReg, RegexOptions.IgnoreCase); foreach (Match match in linkMatchCollection) if (match.Success) Console.Write(match.Groups0.Value); public static void Main(string args) Console.WriteLine("請(qǐng)輸入一個(gè)關(guān)鍵字。"); string keyword; keyword = Con
14、sole.ReadLine(); Console.WriteLine("正在從百度上獲取結(jié)果,請(qǐng)稍等"); string input; input = GetHtml(keyword); Regex r = new Regex("<div id="content_left"sS*</div><div style="clear:both;height:0;"></div>", RegexOptions.IgnoreCase); input = r.Match(input).V
15、alue; MainProc(input); Console.ReadKey(true); 程序結(jié)果如下圖所示:通過(guò)上面的例子你應(yīng)該明白怎樣使用.NET/C# 獲取百度搜索結(jié)果項(xiàng)了吧,程序可以直接使用,如果沒(méi)有得到結(jié)果說(shuō)明是百度搜索的結(jié)構(gòu)變了,請(qǐng)按程序思路改正。Ok, 我們看到此時(shí)的搜索結(jié)果的url 都是被 被百度重定向過(guò)后的url 地址。 都是以 開(kāi)頭的。那么我們需要再多做一點(diǎn)才能得到真正的url地址。我們用C# Get一下發(fā)現(xiàn)其實(shí)訪問(wèn)的是一個(gè)包含我們目標(biāo)網(wǎng)址的一個(gè)網(wǎng)頁(yè)。再多用一次正則去或者真正的目標(biāo)網(wǎng)頁(yè)的url就好了。 public static string GetTheRedirect
16、Url(string originalAddress) string redirectUrl="" HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(originalAddress); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); redirectUrl =(String) response.ResponseUri.AbsoluteUri; Stream ReceiveStream = response.GetR
17、esponseStream(); Encoding encode = System.Text.Encoding.GetEncoding("utf-8"); StreamReader readStream = new StreamReader(ReceiveStream, encode); Char read = new Char256; / Read 256 charcters at a time. int count = readStream.Read(read, 0, 256); Console.WriteLine("HTML.rn"); while (count > 0) String str = new String(read, 0, count); count = readStream.Read(read, 0, 256); String patternstr = "url=s*(?:"(?<1>"*)"|(?<1>S+)"></noscript>" Regex pattern = new Regex( patternstr, RegexOption
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 個(gè)性化家庭收養(yǎng)協(xié)議2024版版
- 二零二五年度履約保證金協(xié)議書(shū)范本:文化旅游項(xiàng)目2篇
- 醫(yī)療器械2025年度原材料供應(yīng)與加工合作協(xié)議3篇
- 2025年度智慧農(nóng)業(yè)灌溉增壓泵供應(yīng)與安裝服務(wù)合同3篇
- 二零二五年度城市更新項(xiàng)目存量房買賣合作框架協(xié)議2篇
- 二零二五版煤礦股權(quán)轉(zhuǎn)讓及礦山安全生產(chǎn)責(zé)任書(shū)4篇
- 2025版園藝用樹(shù)苗買賣合同規(guī)范范本3篇
- 二零二五年度市場(chǎng)分析預(yù)測(cè)專家顧問(wèn)聘請(qǐng)書(shū)3篇
- 2025年度財(cái)務(wù)咨詢與投資分析服務(wù)合同范本集合2篇
- 中小學(xué)階段學(xué)生假期培訓(xùn)協(xié)議樣本版
- 2024年供應(yīng)鏈安全培訓(xùn):深入剖析與應(yīng)用
- 飛鼠養(yǎng)殖技術(shù)指導(dǎo)
- 壞死性筋膜炎
- 整式的加減單元測(cè)試題6套
- 股權(quán)架構(gòu)完整
- 山東省泰安市2022年初中學(xué)業(yè)水平考試生物試題
- 注塑部質(zhì)量控制標(biāo)準(zhǔn)全套
- 人教A版高中數(shù)學(xué)選擇性必修第一冊(cè)第二章直線和圓的方程-經(jīng)典例題及配套練習(xí)題含答案解析
- 銀行網(wǎng)點(diǎn)服務(wù)禮儀標(biāo)準(zhǔn)培訓(xùn)課件
- 二年級(jí)下冊(cè)數(shù)學(xué)教案 -《數(shù)一數(shù)(二)》 北師大版
- 晶體三極管資料
評(píng)論
0/150
提交評(píng)論