LoginSignup
2
2

More than 5 years have passed since last update.

php-phantomjsで取得したhtmlをphpQueryでスクレイピング

Posted at

経緯

JSによるレンダリング後のhtmlをスクレイピングしたかったので、phantomjsを使用。
他のページはそういう感じではなく、phpQueryでスクレイピングしていた。
そのためこういう事になりました。

方法

理由はよくわからんが、いい感じになってくれないので、
DOMDocumentにしてからphpQueryに食わせないといけなかった。

//phantomjsでhtmlをとってきて
$client = Client::getInstance();
$client->getEngine()->setPath(PHANTOMJS_PATH);
$request = $client->getMessageFactory()->createRequest();
$response = $client->getMessageFactory()->createResponse();
$request->setUrl($url);
$client->send($request, $response);
$html = $response->getContent();

//DOMDocumentにする
$dom = new DOMDocument;
@$dom->loadHTML($html); //$htmlになんらかのHTML的invalidがあるので、@をつける
$dom->saveHTML();

//そしてphpQueryでスクレイピングする
$doc = new phpQuery::newDocument($dom);

確認した環境は PHP 7.1.16 です。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2