一直想著整理出網頁抓取的具體實現功能**,方便大家指正,也方便自己學習修正。當然這個並不是針對所有網頁,自己寫的功能有限,只能針對某一特定結構的網頁進行資料採集,如果有更好的方法,請大家不吝指教,在此謝過!
一、抓取網頁內容:
網上可以搜尋到很多抓取網頁的**,以下這個方法是我搜到的乙個供參考:
///
/// 獲取網頁全部源**
//////
/要訪問的**位址
///目標網頁的編碼,如果傳入的是null或者"",那就自動分析網頁的編碼
///public
static
string
gethtml(string url, params
string charsets)
webclient mywebclient = new webclient(); //建立webclient例項mywebclient
// 需要注意的:
//有的網頁可能下不下來,有種種原因比如需要cookie,編碼問題等等
//這是就要具體問題具體分析比如在頭部加入cookie
// webclient.headers.add("cookie", cookie);
//這樣可能需要一些過載方法.根據需要寫就可以了
//獲取或設定用於對向 internet 資源的請求進行身份驗證的網路憑據.
mywebclient.credentials = credentialcache.defaultcredentials;
//如果伺服器要驗證使用者名稱,密碼
//networkcredential mycred = new networkcredential(struser, strpassword);
= mycred;
byte mydatabuffer = mywebclient.downloaddata(url);
string strwebdata = encoding.default.getstring(mydatabuffer);
//獲取網頁字元編碼描述資訊
match charsetmatch = regex.match(strwebdata, ", regexoptions.ignorecase | regexoptions.multiline);
string webcharset = charsetmatch.groups[2].value;
if (charset == null || charset == "")
charset = webcharset;
if (charset != null && charset != "" && encoding.getencoding(charset) != encoding.default)
else
return strwebdata;
}catch (exception e)
}
二、網頁**處理與分類匯入資料庫
網頁處理是採用的正規表示式進行匹配查詢,包括html標籤的匹配、空格空行的匹配等。
public string getclasses(string str)
classname += "|" + bs3;
regex rgx = new regex("([^]*)(.*?)" + bs3 + "
"); str = rgx.replace(str, "");
}str = new regex("(\r\n)*[(\\t)*]").replace(str, "");
int index_0 = str.indexof("
"); if (index_0 == 74 || index_0 == 29)}}
classname += "]"
; }}}
int index_1 = str.indexof("");
if (index_1 < 45)
}return classname;
}
三、觸發採集
前台**:
輸入**:id="textbox1"
runat="server"
width="400">>
id="button2"
runat="server"
text="提交"
onclick="button2_click" />
id="textbox2"
runat="server"
textmode="multiline"
rows="30"
columns="100">
asp:textbox>
後台事件:
protected
void button2_click(object sender, eventargs e)
}
本文只能為做網頁採集提供乙個思路,具體實現還需根據實際情況進行驗證修改。
ps:涉及的正則內容
//s 匹配空格(帶轉義字元)
(\r\n)* 匹配空行及換行
(\t)* 匹配製表符
網頁資料抓取 爬蟲
資料抓取其實從字面意思就知道它是抓取資料的,在網際網路世界中,資料量是乙個非常大的。有時候靠人為去獲取資料這是乙個非常不明智的。尤其是你需要的資料來自很多不同的地方。網路爬蟲是是一種按照一定的規則,自動地抓取網際網路 資訊的程式或者指令碼。它主要抓取形式有兩種 1種是抓取網頁鏈結,通過url鏈結得到...
網頁抓取 PHP實現網頁爬蟲方式小結
抓取某乙個網頁中的內容,需要對dom樹進行解析,找到指定節點後,再抓取我們需要的內容,過程有點繁瑣。lz總結了幾種常用的 易於實現的網頁抓取方式,如果熟悉jquery選擇器,這幾種框架會相當簡單。一 ganon 文件 測試 抓取我的 首頁所有class屬性值是focus的div元素,並且輸出clas...
網頁抓取 PHP實現網頁爬蟲方式小結
抓取某乙個網頁中的內容,需要對dom樹進行解析,找到指定節點後,再抓取我們需要的內容,過程有點繁瑣。lz總結了幾種常用的 易於實現的網頁抓取方式,如果熟悉jquery選擇器,這幾種框架會相當簡單。一 ganon 文件 測試 抓取我的 首頁所有class屬性值是focus的div元素,並且輸出clas...