DomCrawler

Html 및 xml 문서의 dom을 찾는 패키지이다.
주로 html crawling 할때 사용한다.

install

composer require symfony/dom-crawler

usage

use Symfony\Component\DomCrawler\Crawler;
.........
$crawler = new Crawler($html);

foreach ($crawler as $domElement) {
  var_dump($domElement->nodeName);
}

usage with GuzzleHttp

use GuzzleHttp\Client;
use Symfony\Component\DomCrawler\Crawler;
.........

$client = new Client();
$crawler = new Crawler();

$response = $client->request('GET', $url);
$html = $response->getBody()->getContents();
$crawler->addHTMLContent($html, 'UTF-8');

$logs = $crawler->filter('table')->filter('tr')->each(function ($tr, $i) {
  return $tr->filter('td')->each(function ($td, $i) {
    return trim($td->text());
  });
});

Adding the Content

$crawler = new Crawler('<html><body/></html>');

$crawler->addHtmlContent('<html><body/></html>'); // UTF-8 encoding 이  default로 된다.
$crawler->addHTMLContent($html, 'UTF-8');
$crawler->addXmlContent('<root><node/></root>');

$crawler->addContent('<html><body/></html>'); // html에서 최적화된 캐릭터셑을 설정하지만 어떤 케릭터셑이 주어지지 않은 경우 ISO-8859-1 을 디폴트로 한다.
$crawler->addContent('<root><node/></root>', 'text/xml');

$crawler->add('<html><body/></html>');
$crawler->add('<root><node/></root>');

solution 1

가끔 head 나 javascript 가 너무 많은 경우 data를 불러오지 못하는 경우가 있다.

  • install the masterminds/html5 optional dependency, which will make dom-crawler use it to parse your HTML (as you use the HTML5 doctype)
  • wrap the content of your script in a CDATA section to make it parseable by the XML-based parser of libxml

그러나 위와 같은 방식이 힘들경우 특정 부분을 아예 없애버리고 작업하는 것이 좋다.

$html = $response->getBody()->getContents(); // ->getContents();
$html = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $html );
$crawler->addHTMLContent($html, 'UTF-8');
평점을 남겨주세요
평점 : 2.5
총 투표수 : 1