最近想寫一個程式用 HttpWebRequest 自動擷取網路上的資料,但每次只要Create一個新的HttpWebRequest就等於是一次新的連線。而SessionID也會不同,好像沒辦法做到像IE一樣只要程式不關掉就會維持同一個Session。
而上述情況則導致某些網站無法取得資料。 原因為某些網站位防止被程式抓圖,無名、PChome 都有針對抓圖軟體做防護與阻擋,你不知道他背後的阻擋方式時,就比較難處理。 一般最簡單的阻擋方式會看推薦網址跟 Session ,沒有推薦網址或是推薦網址不正確,踢掉,新開的 Session 踢掉,或是在推薦網址內加 Session 代號,兩者比對不同,踢掉。
這還是一般的防護法,有沒有再加上其他的防護法,就看各家廠商如何去玩。 另外還有針對短時間的連結數做統計,比如說,一個人不可能 1 分鐘內看 30 張圖片(包含網路傳輸所需要的時間延遲),在 1 分鐘內超過 30 個要求的話,就鎖 ip 5 分鐘 ~ 1 小時之類的,來中斷自動程式的連續性。 要抓特定網站的,要先試出他的規則才能針對規則去寫,當規則被破時,服務廠商可能隨時會換新規則,來防止被自動程式繼續抓檔。 在這邊先提出HttpWebRequest 如何保留 Session的寫法。
1 | |
2 | |
3 | Dim session As New CookieContainer |
4 | '定義目標URL |
5 | Dim url As String = "http://www.yahoo.com.tw" |
6 | '宣告WebRequest物件 |
7 | Dim myRequest As System.Net.WebRequest = System.Net.WebRequest.Create(Url) |
8 | myRequest.CookieContainer = session |
9 | '取得網頁資訊流 |
10 | Dim myResponse As System.Net.WebResponse = myRequest.GetResponse() |
11 | '宣告StreamReader讀取資料 |
12 | Dim sr As System.IO.StreamReader = New System.IO.StreamReader(myResponse.GetResponseStream),System.Text.Encoding.Default) |
13 | '資料讀取到字串變數中 |
14 | Dim content As String = sr.ReadToEnd() |
view plain | print | ? |
1 | |
2 | |
3 | 第二個要開啟的網址 |
4 | '定義目標URL |
5 | Dim url As String = "http://www.yahoo.com.tw" |
6 | '宣告WebRequest物件 |
7 | Dim myRequest2 As System.Net.WebRequest = System.Net.WebRequest.Create(Url) |
8 | myRequest2.Method = "GET" |
9 | myRequest2.CookieContainer = myRequest.CookieContainer |
10 | '取得網頁資訊流 |
11 | Dim myResponse As System.Net.WebResponse = myRequest2.GetResponse() |
12 | '宣告StreamReader讀取資料 |
13 | Dim sr As System.IO.StreamReader = New System.IO.StreamReader(myResponse.GetResponseStream),System.Text.Encoding.Default) |
14 | '資料讀取到字串變數中 |
15 | Dim content As String = sr.ReadToEnd() |
view plain | print | ? |
參考資料 MSDN CookieContainer 類別
http://msdn2.microsoft.com/zh-tw/library/system.net.cookiecontainer(vs.80).aspx MSDN HttpWebRequest
類別
http://msdn2.microsoft.com/zh-tw/library/system.net.httpwebrequest(vs.80).aspx
藍色小舖討論串
http://www.blueshop.com.tw/board/show.asp?subcde=BRD200705270921161RX&fumcde=FUM20041006161839LRJ
http://www.blueshop.com.tw/board/show.asp?subcde=BRD20050410004136160&fumcde=FUM20050124191756KKC&rplcnt=1
http://epaper.blueshop.com.tw/board/show.asp?subcde=BRD20061224102257PSH&fumcde=FUM20050124192253INM&rplcnt=2 yaodong Blog
http://blog.joycode.com/yaodong/archive/2004/10/10/35129.aspx