IT TIP

PHP에서 웹 스크레이퍼를 구현하는 방법은 무엇입니까?

itqueen 2020. 12. 1. 20:20
반응형

PHP에서 웹 스크레이퍼를 구현하는 방법은 무엇입니까?


웹 스크래핑에 유용한 내장 PHP 기능은 무엇입니까? PHP로 웹 스크래핑 속도를 높이는 데 유용한 리소스 (웹 또는 인쇄)는 무엇입니까?


스크래핑은 일반적으로 3 단계로 구성됩니다.

  • 먼저 요청을 지정된 URL로 가져 오거나 게시합니다.
  • 다음으로 응답으로 반환되는 html을받습니다.
  • 마지막으로 긁어 내고 싶은 텍스트를 HTML에서 파싱합니다.

1 단계와 2 단계를 수행하기 위해 아래는 Curl을 사용하여 GET 또는 POST를 사용하여 웹 페이지를 가져 오는 간단한 PHP 클래스입니다. HTML을 되찾은 후 정규 표현식을 사용하여 스크랩하려는 텍스트를 파싱하여 3 단계를 수행합니다.

정규식의 경우 제가 가장 좋아하는 자습서 사이트는 다음과 같습니다. 정규식 자습서

RegEx로 작업하는 데 가장 좋아하는 프로그램은 Regex Buddy 입니다. 구매할 의사가 없더라도 해당 제품의 데모를 시도해 보는 것이 좋습니다. 이것은 매우 귀중한 도구이며 선택한 언어 (php 포함)로 만든 정규식에 대한 코드를 생성 할 수도 있습니다.

용법:

$curl = new Curl(); $html = $curl->get("http://www.google.com");

// now, do your regex work against $html

PHP 클래스 :



<?php

class Curl
{       

    public $cookieJar = "";

    public function __construct($cookieJarFile = 'cookies.txt') {
        $this->cookieJar = $cookieJarFile;
    }

    function setup()
    {


        $header = array();
        $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
        $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
        $header[] =  "Cache-Control: max-age=0";
        $header[] =  "Connection: keep-alive";
        $header[] = "Keep-Alive: 300";
        $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
        $header[] = "Accept-Language: en-us,en;q=0.5";
        $header[] = "Pragma: "; // browsers keep this blank.


        curl_setopt($this->curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7');
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($this->curl,CURLOPT_COOKIEJAR, $this->cookieJar); 
        curl_setopt($this->curl,CURLOPT_COOKIEFILE, $this->cookieJar);
        curl_setopt($this->curl,CURLOPT_AUTOREFERER, true);
        curl_setopt($this->curl,CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($this->curl,CURLOPT_RETURNTRANSFER, true);  
    }


    function get($url)
    { 
        $this->curl = curl_init($url);
        $this->setup();

        return $this->request();
    }

    function getAll($reg,$str)
    {
        preg_match_all($reg,$str,$matches);
        return $matches[1];
    }

    function postForm($url, $fields, $referer='')
    {
        $this->curl = curl_init($url);
        $this->setup();
        curl_setopt($this->curl, CURLOPT_URL, $url);
        curl_setopt($this->curl, CURLOPT_POST, 1);
        curl_setopt($this->curl, CURLOPT_REFERER, $referer);
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $fields);
        return $this->request();
    }

    function getInfo($info)
    {
        $info = ($info == 'lasturl') ? curl_getinfo($this->curl, CURLINFO_EFFECTIVE_URL) : curl_getinfo($this->curl, $info);
        return $info;
    }

    function request()
    {
        return curl_exec($this->curl);
    }
}

?>


간단한 PHP 웹 스크레이퍼 인 Goutte를 추천 합니다.

사용 예 :-

Goutte 클라이언트 인스턴스 (를 확장 함 Symfony\Component\BrowserKit\Client)를 만듭니다 .

use Goutte\Client;

$client = new Client();

다음 request()메소드로 요청하십시오 .

$crawler = $client->request('GET', 'http://www.symfony-project.org/');

request메서드는 Crawler객체 ( Symfony\Component\DomCrawler\Crawler)를 반환합니다 .

링크를 클릭하십시오 :

$link = $crawler->selectLink('Plugins')->link();
$crawler = $client->click($link);

양식 제출 :

$form = $crawler->selectButton('sign in')->form();
$crawler = $client->submit($form, array('signin[username]' => 'fabien', 'signin[password]' => 'xxxxxx'));

데이터 추출 :

$nodes = $crawler->filter('.error_list');

if ($nodes->count())
{
  die(sprintf("Authentification error: %s\n", $nodes->text()));
}

printf("Nb tasks: %d\n", $crawler->filter('#nb_tasks')->text());

ScraperWiki 는 꽤 흥미로운 프로젝트입니다. Python, Ruby 또는 PHP로 온라인 스크레이퍼를 구축 할 수 있도록 도와줍니다. 몇 분만에 간단한 시도를 할 수있었습니다.


If you need something that is easy to maintain, rather than fast to execute, it could help to use a scriptable browser, such as SimpleTest's.


here is another one: a simple PHP Scraper without Regex.


Scraping can be pretty complex, depending on what you want to do. Have a read of this tutorial series on The Basics Of Writing A Scraper In PHP and see if you can get to grips with it.

You can use similar methods to automate form sign ups, logins, even fake clicking on Ads! The main limitations with using CURL though are that it doesn't support using javascript, so if you are trying to scrape a site that uses AJAX for pagination for example it can become a little tricky...but again there are ways around that!


file_get_contents() can take a remote URL and give you the source. You can then use regular expressions (with the Perl-compatible functions) to grab what you need.

Out of curiosity, what are you trying to scrape?


I'd either use libcurl or Perl's LWP (libwww for perl). Is there a libwww for php?


Scraper class from my framework:

<?php

/*
    Example:

    $site = $this->load->cls('scraper', 'http://www.anysite.com');
    $excss = $site->getExternalCSS();
    $incss = $site->getInternalCSS();
    $ids = $site->getIds();
    $classes = $site->getClasses();
    $spans = $site->getSpans(); 

    print '<pre>';
    print_r($excss);
    print_r($incss);
    print_r($ids);
    print_r($classes);
    print_r($spans);        

*/

class scraper
{
    private $url = '';

    public function __construct($url)
    {
        $this->url = file_get_contents("$url");
    }

    public function getInternalCSS()
    {
        $tmp = preg_match_all('/(style=")(.*?)(")/is', $this->url, $patterns);
        $result = array();
        array_push($result, $patterns[2]);
        array_push($result, count($patterns[2]));
        return $result;
    }

    public function getExternalCSS()
    {
        $tmp = preg_match_all('/(href=")(\w.*\.css)"/i', $this->url, $patterns);
        $result = array();
        array_push($result, $patterns[2]);
        array_push($result, count($patterns[2]));
        return $result;
    }

    public function getIds()
    {
        $tmp = preg_match_all('/(id="(\w*)")/is', $this->url, $patterns);
        $result = array();
        array_push($result, $patterns[2]);
        array_push($result, count($patterns[2]));
        return $result;
    }

    public function getClasses()
    {
        $tmp = preg_match_all('/(class="(\w*)")/is', $this->url, $patterns);
        $result = array();
        array_push($result, $patterns[2]);
        array_push($result, count($patterns[2]));
        return $result;
    }

    public function getSpans(){
        $tmp = preg_match_all('/(<span>)(.*)(<\/span>)/', $this->url, $patterns);
        $result = array();
        array_push($result, $patterns[2]);
        array_push($result, count($patterns[2]));
        return $result;
    }

}
?>

The curl library allows you to download web pages. You should look into regular expressions for doing the scraping.

참고URL : https://stackoverflow.com/questions/26947/how-to-implement-a-web-scraper-in-php

반응형