在使用爬蟲進行一些數據爬取的時候,難免會碰上IP被封的情況,因此提前做個准備,寫了一個簡單的程序先爬取一些代理IP。
public void downIP() throws IOException { // 需要爬取IP信息的網站地址 String url = "http://www.66ip.cn/areaindex_1/1.html"; // 動態模擬請求數據 CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(url); // 模擬瀏覽器瀏覽(user-agent的值可以通過瀏覽器瀏覽,查看發出請求的頭文件獲取) httpGet.setHeader("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36"); CloseableHttpResponse response = httpclient.execute(httpGet); // 獲取響應狀態碼 int statusCode = response.getStatusLine().getStatusCode(); try { HttpEntity entity = response.getEntity(); // 如果狀態響應碼為200,則獲取html實體內容或者json文件 if (statusCode == 200) { // 轉一下碼 String html = EntityUtils.toString(entity, "gb2312"); // 提取HTML Document doc = Jsoup.parse(html); // 下面是根據頁面html代碼來編寫的,根據觀察,發現這個網頁上的數據都在table表格里,因此根據table標簽獲取數據 Elements ulList = doc.select("table"); // 觀察后發現,頁面里存在三個table表格,而我們只需要第三個表格里的數據// 獲取第三個表格中tr標簽里的數據 Elements liList = ulList.get(2).select("tr"); for (Element item : liList) { //這里直接打印出這些數據,需要的可以存進數據庫 System.out.println(item.text()); } // 消耗掉實體 EntityUtils.consume(response.getEntity()); } else { // 消耗掉實體 EntityUtils.consume(response.getEntity()); } } finally { response.close(); } }
直接在主函數里運行這個方法就🆗了。
使用這段代碼需要用到幾個jar包:
之后就可以設置代理IP了
System.getProperties().setProperty("proxySet", "true"); System.getProperties().setProperty("http.proxyHost", "61.135.155.82"); // 設置ip System.getProperties().setProperty("http.proxyPort", "443");// 設置端口號