1. 程式人生 > >資料抓取之反爬蟲規則:使用代理和http頭資訊

資料抓取之反爬蟲規則:使用代理和http頭資訊

之前說個數據抓取遇到的一個坎就是驗證碼,這次來說另外兩個。我們知道web系統可以拿到客戶請求資訊,那麼針對客戶請求的頻率,客戶資訊都會做限制。如果一個ip上的客戶訪問過於頻繁,或者明顯是用程式抓取,肯定是要禁止的。本文針對這兩個問題說下解決方法。

其實針對上述兩個問題,解決方法已經很成熟了,無非就是買代理和在http請求中加入頭資訊偽裝為瀏覽器請求。本文說下具體操作

使用代理

  • 首先購買代理,這個網上賣代理的很多,自己搜尋,而且價格也不貴。
  • 其次就是在程式中使用代理:

      HttpClient httpclient = new DefaultHttpClient();
      httpclient.getCredentialsProvider().setCredentials(
              new AuthScope("代理ip", "代理埠"),
              new UsernamePasswordCredentials("代理使用者名稱","代理密碼"));
    

http請求加入頭資訊

  • 同樣在http請求中加入頭資訊也是很少程式碼搞定:

      HttpGet httpget = new HttpGet(url);
      // 加入頭資訊
      httpget.addHeader("Accept", "text/html");
      httpget.addHeader("Accept-Charset", "utf-8");
      httpget.addHeader("Accept-Encoding", "gzip");
      httpget.addHeader("Accept-Language", "zh-CN,zh");
      httpget.addHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.160 Safari/537.22");
        
      HttpResponse response = httpclient.execute(httpget);
    
  • post請求同樣的方式:

      HttpPost httppost = new HttpPost(url);        
      List<NameValuePair> formparams = param; 
      UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, reqEncoding);
      httppost.setEntity(uefEntity);
      // 加入頭資訊
      httppost.addHeader("Accept", "text/html");
      httppost.addHeader("Accept-Charset", "utf-8");
      httppost.addHeader("Accept-Encoding", "gzip");
      httppost.addHeader("Accept-Language", "en-US,en");
      httppost.addHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.160 Safari/537.22");
    
      HttpResponse response = httpclient.execute(httppost); 
    


也可一去我的個人站點 檢視
或者,歡迎關注俺的微信訂閱號,每天一篇小筆記,每天提高一點點:
公眾好:enilu123