作者:卧颜沉默
链接:https://www.zhihu.com/question/36909173/answer/97643000
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
最近写了一个基于JAVA的知乎爬虫,抓取知乎用户基本信息。
基于HttpClient 4.5的
在服务器上跑着的
到现在抓取了60W+用户
可以对这些数据做简单的挖掘,可以得到很多有趣的信息。
下面说下我的大致思路:
1.首先模拟登录知乎,登录成功后将Cookie序列化到磁盘,不用以后每次都登录(如果不模拟登录,可以直接从浏览器塞入Cookie也是可以的)。
模拟登录通过浏览器F12抓包分析登录过程,需要注意的是验证码的获取和登录过程只能通过一个CloseHttpClient对象完成,CloseHttpClient就好比一个浏览器。不能每次请求都创建对象,不然Cookie失效了。
模拟登录关键代码如下,是通过邮箱登录方式,手机号码登录的方式类似
- 作者:卧颜沉默
- 链接:https://www.zhihu.com/question/36909173/answer/97643000
- 来源:知乎
- 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
- /**
- *
- * @param httpClient Http客户端
- * @param context Http上下文
- * @return
- */
- public boolean login(CloseableHttpClient httpClient, HttpClientContext context){
- String yzm = null;
- String loginState = null;
- HttpGet getRequest = new HttpGet("https://www.zhihu.com/#signin");
- HttpClientUtil.getWebPage(httpClient,context, getRequest, "utf-8", false);
- HttpPost request = new HttpPost("https://www.zhihu.com/login/email");
- List<NameValuePair> formParams = new ArrayList<NameValuePair>();
- yzm = yzm(httpClient, context,"https://www.zhihu.com/captcha.gif?type=login");//肉眼识别验证码
- formParams.add(new BasicNameValuePair("captcha", yzm));
- formParams.add(new BasicNameValuePair("_xsrf", ""));//这个参数可以不用
- formParams.add(new BasicNameValuePair("email", "邮箱"));
- formParams.add(new BasicNameValuePair("password", "密码"));
- formParams.add(new BasicNameValuePair("remember_me", "true"));
- UrlEncodedFormEntity entity = null;
- try {
- entity = new UrlEncodedFormEntity(formParams, "utf-8");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- request.setEntity(entity);
- loginState = HttpClientUtil.getWebPage(httpClient,context, request, "utf-8", false);//登录
- JSONObject jo = new JSONObject(loginState);
- if(jo.get("r").toString().equals("0")){
- System.out.println("登录成功");
- getRequest = new HttpGet("https://www.zhihu.com");
- HttpClientUtil.getWebPage(httpClient,context ,getRequest, "utf-8", false);//访问首页
- HttpClientUtil.serializeObject(context.getCookieStore(),"resources/zhihucookies");//序列化知乎Cookies,下次登录直接通过该cookies登录
- return true;
- }else{
- System.out.println("登录失败" + loginState);
- return false;
- }
- }
- /**
- * 肉眼识别验证码
- * @param httpClient Http客户端
- * @param context Http上下文
- * @param url 验证码地址
- * @return
- */
- public String yzm(CloseableHttpClient httpClient,HttpClientContext context, String url){
- HttpClientUtil.downloadFile(httpClient, context, url, "d:/test/", "1.gif",true);
- Scanner sc = new Scanner(System.in);
- String yzm = sc.nextLine();
- return yzm;
- }
- HttpClientUtil工具类
- /**
- * HttpClient工具类
- */
- public class HttpClientUtil {
- private static Logger logger = MyLogger.getMyLogger(HttpClientUtil.class);
- public static void main(String args []){
- }
- /**
- *
- * @param httpClient HttpClient客户端
- * @param context 上下文
- * @param request 请求
- * @param encoding 字符编码
- * @param isPrintConsole 是否打印到控制台
- * @return 网页内容
- */
- public static String getWebPage(CloseableHttpClient httpClient
- , HttpClientContext context
- , HttpRequestBase request
- , String encoding
- , boolean isPrintConsole){
- CloseableHttpResponse response = null;
- try {
- response = httpClient.execute(request,context);
- } catch (HttpHostConnectException e){
- e.printStackTrace();
- logger.error("HttpHostConnectException",e);
- } catch (IOException e) {
- e.printStackTrace();
- logger.error("IOException",e);
- }
- System.out.println("status---" + response.getStatusLine().getStatusCode());
- BufferedReader rd = null;
- StringBuilder webPage = null;
- try {
- rd = new BufferedReader(
- new InputStreamReader(response.getEntity().getContent(),encoding));
- String line = "";
- webPage = new StringBuilder();
- while((line = rd.readLine()) != null) {
- webPage.append(line);
- if(isPrintConsole){
- System.out.println(line);
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- request.releaseConnection();
- return webPage.toString();
- }
- /**
- * 序列化对象
- * @param object
- * @throws Exception
- */
- public static void serializeObject(Object object,String filePath){
- OutputStream fos = null;
- try {
- fos = new FileOutputStream(filePath);
- ObjectOutputStream oos = new ObjectOutputStream(fos);
- oos.writeObject(object);
- System.out.println("序列化成功");
- oos.flush();
- fos.close();
- oos.close();
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * 反序列化对象
- * @param name
- * @throws Exception
- */
- public static Object antiSerializeMyHttpClient(String name){
- InputStream fis = HttpClientUtil.class.getResourceAsStream(name);
- ObjectInputStream ois = null;
- Object object = null;
- try {
- ois = new ObjectInputStream(fis);
- object = ois.readObject();
- fis.close();
- ois.close();
- } catch (IOException e) {
- e.printStackTrace();
- logger.error("IOException",e);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- logger.error("ClassNotFoundException",e);
- } catch (NullPointerException e){
- e.printStackTrace();
- logger.error("NullPointerException",e);
- }
- System.out.println("反序列化成功 ");
- return object;
- }
- /**
- * 设置Cookies策略
- * @return CloseableHttpClient
- */
- public static CloseableHttpClient getMyHttpClient(){
- CloseableHttpClient httpClient = null;
- RequestConfig globalConfig = RequestConfig.custom()
- .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
- .build();
- httpClient = HttpClients.custom()
- .setDefaultRequestConfig(globalConfig)
- .build();
- return httpClient;
- }
- /**
- * 设置上下文
- * @return HttpClientContext
- */
- public static HttpClientContext getMyHttpClientContext(){
- HttpClientContext context = null;
- context = HttpClientContext.create();
- Registry<CookieSpecProvider> registry = RegistryBuilder
- .<CookieSpecProvider> create()
- .register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory())
- .register(CookieSpecs.BROWSER_COMPATIBILITY,
- new BrowserCompatSpecFactory()).build();
- context.setCookieSpecRegistry(registry);
- return context;
- }
- }
复制代码
|
|