mahadazad/page-scraper

此包最新版本(dev-master)没有提供许可证信息。

dev-master 2014-12-12 05:13 UTC

This package is not auto-updated.

Last update: 2024-09-24 02:57:43 UTC


README

使用几行代码即可轻松实现页面抓取。使用XPath或CSS选择器从任何网站抓取数据。

简介

从有效的xml/html页面解析数据最简单的方法是使用XPath查询。但是获取远程数据的方法可能不同,例如使用简单的file_get_contents函数,该函数使用PHP Streams获取远程页面,可以使用CURL,也可以使用著名的Guzzle库。为了解耦最终产品(即Page)与远程页面获取逻辑,并避免将Page对象置于不稳定状态,我使用了Builder模式。将Page对象传递给包含获取远程页面逻辑的Builder对象,然后将Builder传递给director对象,director对象告诉Builder如何配置Page对象。简而言之

$page = new Page('https://news.ycombinator.com');
$builder = new PageBuilder($page);
$builder->setDataConfig(array(
    'side_links' => array('css' => '.title .comhead'), // use CSS Selector
    'titles'     => '//td[@class="title"]//a/text()', // use XPath
    'links'      => '//td[@class="title"]//a/@href', // use XPath
));
$director = new PageBuilderDirector($builder);
$director->buildPage();
$data = $page->getData();

使用客户端类简化操作

为了避免繁琐的工作,您可以使用Client类来简化生活

$client = new Client(array(
    'url'         => 'https://news.ycombinator.com',
    'data_config' => array(
        'titles' => '//td[@class="title"]//a/text()', // the xpath query
        'links' => '//td[@class="title"]//a/@href', // the xpath query
    ),
));

$page = $client->fetchPage();
$data = $page->getData();

/*
  prints:
   array (
    'titles' => array(
        'title one from the remote page',
        'title two from the remote page',
        'title three from the remote page',
        // so on...
    ),
    'links' => array(
        'http://www.example.com/one',
        'http://www.example.com/two',
        'http://www.example.com/three',
        // so on...
    ),
  )
*/
print_r($data);

话虽如此,您也可以使用客户端的setter方法设置自己的buildersdirectors。请参阅类定义以获取文档。

高级数据解析

data_config可以包含key => value对。其中值可以是有效的xpath查询或回调,该回调接收配置的Page对象,您可以利用它进行高级解析,而key则持有解析结果。例如

$client = new Client(array(
    'url'         => 'https://news.ycombinator.com',
    'data_config' => array(
        'side_links' => '.title .comhead', // use css selector
        'titles' => '//td[@class="title"]//a/text()', // use xpath query
        'links' => function ($page) {
            $links = array();
            $node_list = $page->getXpath()->query('//td[@class="title"]//a/@href');
            foreach($node_list as $node) {
                $links[] = $node->nodeValue;
            }
            return $links;
        },
    ),
));

$page = $client->fetchPage();
$data = $page->getData();

安装

使用composer安装库,在您的composer.json中

{
    "require": {
        "mahadazad/page-scraper": "dev-master"
    }
}

或者运行

php composer.phar require "mahadazad/page-scraper":"dev-master"