php 사용자 데이터 추출 및 분석 실현

12253 단어 파충류
배경 설명:phop 의 curl 을 이용 하여 쓴 파충류,실험 적 으로 5w 사용자 의 기본 정 보 를 얻 었 습 니 다.또한 기어 오 르 는 데 이 터 를 대상 으로 간단 한 분석 을 실시 했다.
php 의 spider 코드 와 사용자 dashboard 의 표현 코드 를 정리 한 후에 github 를 업로드 하고 개인 블 로그 와 공중 번호 에서 코드 라 이브 러 리 를 업데이트 하 며 프로그램 은 오락 과 학습 교류 만 제공 합 니 다.관련 권익 을 침해 하 는 경우 에는 가능 한 한 빨리 본인 에 게 연락 하여 삭제 해 주 십시오.
진상 이 없 으 려 하 다
이동 단 분석 데이터 캡 처

pc 단 분석 데이터 캡 처

전체 기어 오 르 기,분석,표현 과정 은 대략 다음 과 같은 몇 걸음 으로 나 뉘 는데,잡 아 당 기 는 것 은 각각 소개 할 것 이다.
  • curl 은 웹 페이지 데이터
  • 를 알 수 있 습 니 다.
  • 정규 분석 은 웹 데이터
  • 데이터 데이터 입고 와 프로그램 배치
  • 데이터 분석 과 표현
  • curl 웹 페이지 데이터 추출
    PHP 의 curl 확장 은 PHP 가 지원 합 니 다.다양한 서버 와 다양한 종류의 프로 토 콜 을 사용 하여 연결 하고 통신 할 수 있 는 라 이브 러 리 입 니 다.웹 페이지 를 매우 편리 하 게 캡 처 하 는 도구 이 며,동시에 다 중 스 레 드 확장 을 지원 합 니 다.
    이 프로그램 은 대외 적 으로 사용자 가 방문 하 는 개인 정보 페이지 를 캡 처 합 니 다.https://www.zhihu.com/people/xxx캡 처 과정 은 사용자 쿠키 를 휴대 해 야 페이지 를 가 져 올 수 있 습 니 다.직접 코드
    페이지 쿠키 가 져 오기

    // , , , cookie
    document.cookie
    "_za=67254197-3wwb8d-43f6-94f0-fb0e2d521c31; _ga=GA1.2.2142818188.1433767929; q_c1=78ee1604225d47d08cddd8142a08288b23|1452172601000|1452172601000; _xsrf=15f0639cbe6fb607560c075269064393; cap_id="N2QwMTExNGQ0YTY2NGVddlMGIyNmQ4NjdjOTU0YTM5MmQ=|1453444256|49fdc6b43dc51f702b7d6575451e228f56cdaf5d"; __utmt=1; unlock_ticket="QUJDTWpmM0lsZdd2dYQUFBQVlRSlZUVTNVb1ZaNDVoQXJlblVmWGJ0WGwyaHlDdVdscXdZU1VRPT0=|1453444421|c47a2afde1ff334d416bafb1cc267b41014c9d5f"; __utma=51854390.21428dd18188.1433767929.1453187421.1453444257.3; __utmb=51854390.14.8.1453444425011; __utmc=51854390; __utmz=51854390.1452846679.1.dd1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); __utmv=51854390.100-1|2=registration_date=20150823=1^dd3=entry_date=20150823=1"
    개인 센터 페이지 캡 처
    curl 을 통 해 쿠키 를 휴대 하고 본인 센터 페이지 를 먼저 캡 처 합 니 다.
    
    /**
     *                 
     * 
     * @param $username str :    flag
     * @return boolean   :      
     */
    public function spiderUser($username)
    {
      $cookie = "xxxx" ;
      $url_info = 'http://www.zhihu.com/people/' . $username; //  cui-xiao-zhuai    ID,     url    id
      $ch = curl_init($url_info); //     
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLOPT_COOKIE, $cookie); //    COOKIE
      curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // curl_exec()              ,       。
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
      $result = curl_exec($ch);
    
       file_put_contents('/home/work/zxdata_ch/php/zhihu_spider/file/'.$username.'.html',$result);
       return true;
     }
    정규 분석 웹 데이터 분석 새로운 링크 를 한층 더
    캡 처 한 웹 페이지 를 저장 합 니 다.알 고 있 는 페이지 분석 을 통 해 개인 중심 페이지 에서 주석 과 일부 좋아요 와 주 목 받 는 사람 을 발견 했다.
    아래 와 같다

    // html ,
    <a class="zm-item-link-avatar avatar-link" href="/people/new-user" data-tip="p$t$new-user">
    ok,이렇게 하면 자신-'팔 로 워-'팔 로 워 의 팔 로 워-'를 통 해...끊임없이 기어 오른다.다음은 정규 매 칭 을 통 해 이 정 보 를 추출 하 는 것 입 니 다.

    //
    preg_match_all('/\/people\/([\w-]+)\"/i', $str, $match_arr);
    // ,
    self::$newUserArr = array_unique(array_merge($match_arr[1], self::$newUserArr));
    여기까지 만 하면 전체 파충류 과정 이 순조롭게 진 행 될 수 있다.
    만약 에 대량의 캡 처 데이터 가 필요 하 다 면curl_multipcntl를 연구 하여 다 중 스 레 드 의 빠 른 캡 처 를 할 수 있 습 니 다.여 기 는 군말 하지 않 습 니 다.
    사용자 데이터 분석,분석 제공
    정규 를 통 해 더 많은 사용자 데 이 터 를 일치 시 키 고 직접 코드 를 올 릴 수 있 습 니 다.
    
    //       
    preg_match('/<img.+src=\"?([^\s]+\.(jpg|gif|bmp|bnp|png))\"?.+>/i', $str, $match_img);
    $img_url = $match_img[1];
    
    //      :
    // <span class="name">   </span>
    preg_match('/<span.+class=\"?name\"?>([\x{4e00}-\x{9fa5}]+).+span>/u', $str, $match_name);
    $user_name = $match_name[1];
    
    //       
    // class bio span   
    preg_match('/<span.+class=\"?bio\"?.+\>([\x{4e00}-\x{9fa5}]+).+span>/u', $str, $match_title);
    $user_title = $match_title[1];
    
    //     
    //<input type="radio" name="gender" value="1" checked="checked" class="male"/>  &nbsp;&nbsp;
    // gender value1 ;     
    preg_match('/<input.+name=\"?gender\"?.+value=\"?1\"?.+([\x{4e00}-\x{9fa5}]+).+\;/u', $str, $match_sex);
    $user_sex = $match_sex[1];
    
    //     
    //<span class="location item" title="  ">
    preg_match('/<span.+class=\"?location.+\"?.+\"([\x{4e00}-\x{9fa5}]+)\">/u', $str, $match_city);
    $user_city = $match_city[1];
    
    //     
    //<span class="employment item" title="       ">       </span>
    preg_match('/<span.+class=\"?employment.+\"?.+\"([\x{4e00}-\x{9fa5}]+)\">/u', $str, $match_employment);
    $user_employ = $match_employment[1];
    
    //     
    // <span class="position item" title="   "><a href="/topic/19590046" title="   " class="topic-link" data-token="19590046" data-topicid="13253">   </a></span>
    preg_match('/<span.+class=\"?position.+\"?.+\"([\x{4e00}-\x{9fa5}]+).+\">/u', $str, $match_position);
    $user_position = $match_position[1];
    
    //     
    // <span class="education item" title="   ">   </span>
    preg_match('/<span.+class=\"?education.+\"?.+\"([\x{4e00}-\x{9fa5}]+)\">/u', $str, $match_education);
    $user_education = $match_education[1];
    
    //     
    // <span class="education-extra item" title='  '>  </span>
    preg_match('/<span.+class=\"?education-extra.+\"?.+>([\x{4e00}-
    \x{9fa5}]+)</u', $str, $match_education_extra);
    $user_education_extra = $match_education_extra[1];
    
    
    //         
    // class="zg-link-litblue"><strong>41    </strong></a>
    preg_match('/class=\"?zg-link-litblue\"?><strong>(\d+)\s.+strong>/i', $str, $match_topic);
    $user_topic = $match_topic[1];
    
    //     
    // <span class="zg-gray-normal">   
    preg_match_all('/<strong>(\d+)<.+<label>/i', $str, $match_care);
    $user_care = $match_care[1][0];
    $user_be_careed = $match_care[1][1];
    
    //      
    // <span class="zg-gray-normal">      <strong>17</strong>    </span>
    preg_match('/class=\"?zg-gray-normal\"?.+>(\d+)<.+span>/i', $str, $match_browse);
    $user_browse = $match_browse[1];
    
    캡 처 과정 에서 조건 이 있 으 면 반드시 redis 를 통 해 입고 해 야 캡 처 와 입고 효율 을 높 일 수 있 습 니 다.조건 이 없 으 면 sql 로 만 최적화 할 수 있 습 니 다.여기 서 심 덕 이 몇 발 왔 습 니까?
    데이터베이스 시트 디자인 색인 은 반드시 신중 해 야 한다.spider 가 기어 오 르 는 과정 에서 사용자 이름 을 제안 합 니 다.좌우 필드 는 색인 을 하지 마 십시오.메 인 키 를 포함 하여 하지 마 십시오. 5000 w 의 데 이 터 를 생각해 보 세 요.매번 하 나 를 추가 할 때마다 색인 을 만 드 는 데 얼마나 소모 되 는 지 알 아 보 세 요.캡 처 가 완료 되면 데 이 터 를 분석 해 야 할 때 색인 을 대량으로 만 듭 니 다.
    데이터 입고 와 업데이트 작업 은 반드시 대량으로 해 야 합 니 다.mysql 에서 공식 적 으로 제시 한 삭제 건의 와 속도:http://dev.mysql.com/doc/refman/5.7/en/insert-speed.html
    
    #          
    INSERT INTO yourtable VALUES (1,2), (5,5), ...;
    배치 조작.프로그램 이 캡 처 과정 에서 이상 하 게 끊 길 수 있 습 니 다.효율 적 이 고 안정 적 인 스 크 립 트 를 만 들 기 위해 가능 한 한 타 이 밍 스 크 립 트 를 작성 하 십시오.일정 시간 마다 해치 우 고 다시 뛰 면 이상 하 게 끊 어도 귀중 한 시간 을 낭비 하지 않 습 니 다.왜냐하면 time is money 입 니 다.
    
    #!/bin/bash
    
    #   
    ps aux |grep spider |awk '{print $2}'|xargs kill -9
    sleep 5s
    
    #    
    nohup /home/cuixiaohuan/lamp/php5/bin/php /home/cuixiaohuan/php/zhihu_spider/spider_new.php &  
    데이터 분석 표현
    데이터 의 표현 은 주로 echarts 3.0 을 사용 하 는데 모 바 일 호환성 이 좋 은 것 같 습 니 다.이동 단 을 호 환 하 는 페이지 응답 식 레이아웃 은 주로 몇 가지 간단 한 css 제 어 를 통 해 이 루어 집 니 다.코드 는 다음 과 같 습 니 다.
    
    //       
    preg_match('/<img.+src=\"?([^\s]+\.(jpg|gif|bmp|bnp|png))\"?.+>/i', $str, $match_img);
    $img_url = $match_img[1];
    
    //      :
    // <span class="name">   </span>
    preg_match('/<span.+class=\"?name\"?>([\x{4e00}-\x{9fa5}]+).+span>/u', $str, $match_name);
    $user_name = $match_name[1];
    
    //       
    // class bio span   
    preg_match('/<span.+class=\"?bio\"?.+\>([\x{4e00}-\x{9fa5}]+).+span>/u', $str, $match_title);
    $user_title = $match_title[1];
    
    //     
    //<input type="radio" name="gender" value="1" checked="checked" class="male"/>  &nbsp;&nbsp;
    // gender value1 ;     
    preg_match('/<input.+name=\"?gender\"?.+value=\"?1\"?.+([\x{4e00}-\x{9fa5}]+).+\;/u', $str, $match_sex);
    $user_sex = $match_sex[1];
    
    //     
    //<span class="location item" title="  ">
    preg_match('/<span.+class=\"?location.+\"?.+\"([\x{4e00}-\x{9fa5}]+)\">/u', $str, $match_city);
    $user_city = $match_city[1];
    
    //     
    //<span class="employment item" title="       ">       </span>
    preg_match('/<span.+class=\"?employment.+\"?.+\"([\x{4e00}-\x{9fa5}]+)\">/u', $str, $match_employment);
    $user_employ = $match_employment[1];
    
    //     
    // <span class="position item" title="   "><a href="/topic/19590046" title="   " class="topic-link" data-token="19590046" data-topicid="13253">   </a></span>
    preg_match('/<span.+class=\"?position.+\"?.+\"([\x{4e00}-\x{9fa5}]+).+\">/u', $str, $match_position);
    $user_position = $match_position[1];
    
    //     
    // <span class="education item" title="   ">   </span>
    preg_match('/<span.+class=\"?education.+\"?.+\"([\x{4e00}-\x{9fa5}]+)\">/u', $str, $match_education);
    $user_education = $match_education[1];
    
    //     
    // <span class="education-extra item" title='  '>  </span>
    preg_match('/<span.+class=\"?education-extra.+\"?.+>([\x{4e00}-
    \x{9fa5}]+)</u', $str, $match_education_extra);
    $user_education_extra = $match_education_extra[1];
    
    
    //         
    // class="zg-link-litblue"><strong>41    </strong></a>
    preg_match('/class=\"?zg-link-litblue\"?><strong>(\d+)\s.+strong>/i', $str, $match_topic);
    $user_topic = $match_topic[1];
    
    //     
    // <span class="zg-gray-normal">   
    preg_match_all('/<strong>(\d+)<.+<label>/i', $str, $match_care);
    $user_care = $match_care[1][0];
    $user_be_careed = $match_care[1][1];
    
    //      
    // <span class="zg-gray-normal">      <strong>17</strong>    </span>
    preg_match('/class=\"?zg-gray-normal\"?.+>(\d+)<.+span>/i', $str, $match_browse);
    $user_browse = $match_browse[1];
    
    부족 과 학습 대기
    전체 과정 에서 phop,셸,js,css,html,정규 등 언어 와 배치 등 기초 지식 과 관련 되 지만 개선 하고 보완 해 야 할 부분 이 많 습 니 다.
  • phop 은 multicul 을 이용 하여 다 중 스 레 드 를 진행 합 니 다.
  • 정규 매 칭 최적화
  • 배치 와 캡 처 과정 은 redis 로 저장 소 를 향상 시킨다
  • 이동 단 레이아웃 의 호환성 향상
  • js 의 모듈 화 와 sas 쓰기 css.
  • 좋은 웹페이지 즐겨찾기