GitHub:https://github.com/MatrixSeven/ZhihuSpider(已完結,歡迎 Star)
數據下載:README.md 內含 MySQL 匯出文件。
知乎 PC 端介面結構複雜,移動端(m.zhihu.com)結構簡潔,適合解析。必須在請求頭設置 User-Agent:
User-Agent: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.76 Mobile Safari/537.36
代碼:
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) ...");
實際抓包發現,關注/粉絲列表走 PC Web API,返回 JSON,無需 Jsoup 解析 HTML:
GET https://www.zhihu.com/api/v4/members/{user}/followers?
per_page=10&include=data[*].employments,cover_url,allow_message,answer_count,
articles_count,favorite_count,follower_count,gender,is_followed,
message_thread_token,is_following,badge[?(type=best_answerer)].topics
&limit=10&offset=0
需在 Cookie 中攜帶 z_c0 欄位。JSON 結構包含 paging(分頁資訊)與 data(用戶陣列)。
while (!paging.is_end) {
String nextUrl = paging.getNext();
HttpGet get = new HttpGet(nextUrl);
get.setHeader("Cookie", cookieWithZc0);
// 執行請求 → 解析 JSON → 入庫 → 更新 paging
}
User-Agent + Cookie(z_c0),否則 403/401。include 需 URLEncode,建議用 URIBuilder 組裝。