時間:2023-04-24 11:45:02 | 來源:網(wǎng)站運營
時間:2023-04-24 11:45:02 來源:網(wǎng)站運營
手擼了一個java爬蟲,發(fā)現(xiàn)了c站這么多大佬:今天我們使用Java語言寫一個爬蟲,用來爬取csdn首頁推薦博客的博主,看看這些博主有多少人在寫微信公眾號。url
,然后將響應的頁面進行解析,將解析到的數(shù)據(jù)保存,同時解析出當前頁面的url,繼續(xù)進行爬取,一直循環(huán)下去,爬取當前網(wǎng)站的內(nèi)容。https://www.csdn.net/
,f12
查看目標元素<a></a>
中,其二是博客地址的格式為https://blog.csdn.net/
+"用戶名"+/article/details/
+"文章標識"(記住這個博客地址,后面有用)。f12
來查看DOM元素,發(fā)現(xiàn)這一塊內(nèi)容在id=asideCustom
的<div>中。a
標簽a
標簽,根據(jù)博客地址格式,匹配到所有的博客地址id=asideCustom
的<div>httpclient
用于網(wǎng)絡請求,另一個是用來解析DOM元素的jsoup
。<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.10</version></dependency>?<!-- 添加jsoup支持 --><dependency> <groupId>org.jsoup</groupId> <artifactId>jsoup</artifactId> <version>1.10.1</version></dependency>
網(wǎng)絡調(diào)用偽代碼public static ArrayList<Document> HttpUtil(HashSet<String> urls){ CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; ArrayList<Document> list = new ArrayList<>(); try { for(String url : urls){ HttpGet request = new HttpGet(url); response = httpClient.execute(request);? //判斷響應狀態(tài)為200,請求成功,進行處理 if(response.getStatusLine().getStatusCode() == 200) { HttpEntity httpEntity = response.getEntity(); String html = EntityUtils.toString(httpEntity, "utf-8"); Document document = Jsoup.parse(html); list.add(document); } else { System.out.println("返回狀態(tài)不是200"); } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { HttpClientUtils.closeQuietly(response); HttpClientUtils.closeQuietly(httpClient); } return list;}
調(diào)用及解析偽代碼public static void main(String[] args) {? // 標記有多少博主設置了自定義信息 int i = 0; // 首頁url HashSet<String> url = new HashSet<>(); // 文章urls HashSet<String> articleUrls = new HashSet<>(); url.add("https://www.csdn.net/"); // 爬取csdn首頁 ArrayList<Document> list = HttpUtil(url); // 選擇a標簽 for(Document document : list){ Elements a = document.select("a"); for(Element element : a){ // 獲取a中的url // <a href = "https://xxxx"> </a> String href = element.attr("href"); // 篩選博客地址 if(href.contains("article/details")){ articleUrls.add(href); } } } ArrayList<Document> list2 = HttpUtil(articleUrls); for(Document document : list2){ Element asideCustom = document.getElementById("asideCustom"); if(asideCustom != null){ i++; } } // 輸出爬取的文章數(shù)量 和 設置了自定義信息的博主數(shù)量 System.out.println("爬取的文章數(shù)量="+articleUrls.size()+"/n"+"寫公眾號的博主數(shù)量="+i);}
控制臺輸出信息爬取的文章數(shù)量=25寫公眾號的博主數(shù)量=5
關鍵詞:爬蟲
微信公眾號
版權所有? 億企邦 1997-2025 保留一切法律許可權利。