English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHPCrawl 크롤러 라이브러리를 사용하여 Kugou 곡 목록을 잡는 방법 예제

이 문서는 PHPCrawl 크롤링 라이브러리를 사용하여 크루도그 곡 목록을 추출하는 방법을 설명합니다. 여러분과 공유하고, 구체적으로 다음과 같습니다:

네트워크 크롤링 관련 비디오를 보고 손이 가려워, 무엇인가를 크롤링해보고 싶어졌습니다. 최근 페이스북에서 표정 패키지 전쟁이 치열했고, 모든 표정 패키지를 다 크롤링하려고 했지만, 적절한 VPN을 찾지 못해, 최근 한 달 동안 크루도그의 선택된 음악과 간단한 소개를 로컬로 가져왔습니다. 코드는 조금 무서워 보이지만, 자신감이 없어 올리지 않고 싶었습니다. 그러나 생각을 돌리니, 이는 저의 첫 번째 크롤링이니까... 그래서 이렇게 보기에 좋지 않은 코드가 생겼습니다~~~(데이터 양이 적기 때문에 멀티 프로세스 등을 고려하지 않았지만, PHPCrawl 문서를 보니 PHPCrawl 라이브러리가 저의 생각했던 모든 기능을 포장해 두었음을 발견했습니다. 이를 구현하는 것은 매우 쉬웠습니다)

<?php
header("Content-type:text/html;charset=utf-8");
// It may take a whils to crawl a site ...
set_time_limit(10000);
include("libs/PHPCrawler.class.php");
class MyCrawler extends PHPCrawler {
  function handleDocumentInfo($DocInfo) {
    // Just detect linebreak for output (\-mode, otherwise \
    if (PHP_SAPI == "cli") $lb = "\n";
    else $lb = "<br />";
    $url = $DocInfo->url;
    $pat = "/http:\/\/www\.kugou\.com\/yy\/special\/single\/\d+.html/";
    if(preg_match($pat,$url) > 0){
    $this->parseSonglist($DocInfo);
    }
    flush();
  }
  public function parseSonglist($DocInfo){
    $content = $DocInfo->content;
    $songlistArr = array();
    $songlistArr['raw_url'] = $DocInfo->url;
    //解析歌曲介绍
    $matches = array();
    $pat = "/<span>名称:<\/span>([^(<br)]+)<br/";
    $ret = preg_match($pat,$content,$matches);
    if($ret>0){
      $songlistArr['title'] = $matches[1];
    }else{
      $songlistArr['title'] = '';
    }
    //解析歌曲
    $pat = "/<a title=\"([^\"]+)\" hidefocus=\"/";
    $matches = array();
    preg_match_all($pat,$content,$matches);
    $songlistArr['songs'] = array();
    for($i = 0;$i < count($matches[0]);$i++]{
      $song_title = $matches[1
      array_push($songlistArr['songs'],array('title'=>$song_title));
    }
    echo "<pre>";
    print_r($songlistArr);
    echo "</pre>";
    }
  }
$crawler = new MyCrawler();
// URL to crawl
$start_url="http://www.kugou.com/yy/special/index/1-0-2.html";
$crawler->setURL($start_url);
// Only receive content of files with content-type "text/html"
$crawler->addContentTypeReceiveRule("#text/html#");
//链接扩展
$crawler->addURLFollowRule("#http://www\.kugou\.com/yy/special/single/\d+\.html$# i");
$crawler->addURLFollowRule("#http://www.kugou\.com/yy/special/index/\d+-\d+-2\.html$# i");
// Store and send cookie-data like a browser does
$crawler->enableCookieHandling(true);
// Set the traffic-limit to 1 MB(1000 * 1024) (in bytes,
// for testing we dont want to "suck" the whole site)
//爬取大小无限制
$crawler->setTrafficLimit(0);
// Thats enough, now here we go
$crawler->go();
// At the end, after the process is finished, we print a short
// report (see method getProcessReport() for more information)
$report = $crawler->getProcessReport();
if (PHP_SAPI == "cli") $lb = "\n";
else $lb = "<br />";
echo "Summary: ".$lb;
echo "Links followed: ".$report->links_followed.$lb;
echo "Documents received: ".$report->files_received.$lb;
echo "Bytes received: ".$report->bytes_received." bytes".$lb;
echo "Process runtime: ".$report->process_runtime." sec".$lb; 
?>

PS: 여기서 추가로 제공합니다2매우 편리한 정규 표현식 도구를 참고 사용하기 위해 제공됩니다:

JavaScript 정규 표현식 온라인 테스트 도구:
http://tools.jb51.net/regex/javascript

정규 표현식 온라인 생성 도구:
http://tools.jb51.net/regex/create_reg

PHP와 관련된 더 많은 내용에 대해 관심이 있는 독자는 다음 특집을 확인할 수 있습니다: 《PHP 정규 표현식 사용 요약》、《PHP 배열(Array) 조작 기술大全》、《PHP 기본 문법 입문 강의》、《PHP 연산 및 연산자 사용 요약》、《PHP面向对象程序设计入门教程》、《PHP 네트워크 프로그래밍 기술 요약》、《PHP 문자열(string) 사용 요약》+mysql 데이터베이스 조작 입문 강의》 및 《php 일반 데이터베이스 조작 기술 요약》

이 강의가 PHP 프로그래밍에 도움이 되길 바랍니다.

언급: 본문은 인터넷에서 가져온 것이며, 저작권자는 본인이며, 인터넷 사용자가 자발적으로 기여하고 자체로 업로드한 내용입니다. 이 사이트는 소유권을 가지지 않으며, 인공 편집 처리를하지 않으며, 관련 법적 책임도 부담하지 않습니다. 저작권 위반이 의심되는 내용이 있다면, notice#w로 이메일을 보내 주세요.3codebox.com에 대한 신고를 보내면, #을 @으로 변경하고, 관련 증거를 제공하면, 사이트가 즉시 위반 내용을 삭제합니다.

좋아하는 것