edwinhuish/querylist

简洁、优雅、可扩展的PHP网页爬虫(爬虫/蜘蛛),使用css3 dom选择器,基于DomQuery!

V5.0.9 2020-04-10 04:13 UTC

README

QueryList

QueryList

QueryList是一个简洁、优雅、可扩展的PHP网页爬虫(爬虫/蜘蛛),基于DomQuery

API文档

中文文档

特性

  • 具有与jQuery相同的CSS3 DOM选择器
  • 具有与jQuery相同的DOM操作API
  • 具有通用的列表爬虫程序
  • 拥有强大的HTTP请求套件,易于实现如:模拟着陆、伪造浏览器、HTTP代理等复杂网络请求
  • 具有乱码代码解决方案
  • 具有强大的内容过滤,您可以使用jQuery选择器来过滤内容
  • 具有高度模块化的设计,可扩展性强
  • 具有表达式的API
  • 拥有丰富的插件

通过插件,您可以轻松实现以下功能:

  • 多线程爬取
  • 爬取JavaScript动态渲染页面(PhantomJS/无头WebKit)
  • 图片下载到本地
  • 模拟浏览器行为,如提交表单
  • 网络爬虫
  • .....

要求

  • PHP >= 7.1

安装

通过Composer安装

composer require edwinhuish/querylist

使用

DOM遍历和操作

  • 爬取「GitHub」所有图片链接
QueryList::get('https://github.com')->find('img')->attrs('src');
  • 爬取Google搜索结果
$ql = QueryList::get('https://www.google.co.jp/search?q=QueryList');

$ql->find('title')->text(); //The page title
$ql->find('meta[name=keywords]')->content; //The page keywords

$ql->find('h3>a')->texts(); //Get a list of search results titles
$ql->find('h3>a')->attrs('href'); //Get a list of search results links

$ql->find('img')->src; //Gets the link address of the first image
$ql->find('img:eq(1)')->src; //Gets the link address of the second image
$ql->find('img')->eq(2)->src; //Gets the link address of the third image
// Loop all the images
$ql->find('img')->map(function($img){
	echo $img->alt;  //Print the alt attribute of the image
});
  • 更多使用方法
$ql->find('#head')->append('<div>Append content</div>')->find('div')->htmls();
$ql->find('.two')->children('img')->attrs('alt'); // Get the class is the "two" element under all img child nodes

// Loop class is the "two" element under all child nodes
// map method return Collection object
$data = $ql->find('.two')->children()->map(function (Elements $el){
    // Use "is" to determine the node type
    if($el->is('a')){
        return $el->text();
    }elseif($el->is('img')){
        return $el->alt;
    }
});

$ql->find('a')->attr('href', 'newVal')->removeClass('className')->html('newHtml')->...
$ql->find('div > p')->add('div > ul')->filter(':has(a)')->find('p:first')->nextAll()->andSelf()->...
$ql->find('div.old')->replaceWith( $ql->find('div.new')->clone())->appendTo('.trash')->prepend('Deleted')->...

列表爬取

爬取Google搜索结果列表的标题和链接

$data = QueryList::get('https://www.google.co.jp/search?q=QueryList')
    ->handle(OneAttrPerElementHandler::class) // Extracted Attrs handler need to add before extract()
    ->extract([  // Set the crawl rules
	    'title'=>array('h3','text'),
	    'link'=>array('h3>a','href')
	]);

print_r($data->all());

结果

Array
(
    [0] => Array
        (
            [title] => Angular - QueryList
            [link] => https://angular.io/api/core/QueryList
        )
    [1] => Array
        (
            [title] => QueryList | @angular/core - Angularリファレンス - Web Creative Park
            [link] => http://www.webcreativepark.net/angular/querylist/
        )
    [2] => Array
        (
            [title] => QueryListにQueryを追加したり、追加されたことを感知する | TIPS ...
            [link] => http://www.webcreativepark.net/angular/querylist_query_add_subscribe/
        )
        //...
)

extract()更多使用:

$html = <<<HTML
<ul>
    <li>
        <a href="http://querylist.cc">QueryList Website</a>
        <img src="http://querylist.com/1.jpg" alt="this is picture 1" abc="this is custom attribute">
    </li>
    <li>
        <a href="http://v3.querylist.cc">QueryList V3 doc</a>
        <img src="http://querylist.com/2.jpg" alt="this is picture 2" abc="this is custom attribute 2">
    </li>
</ul>
HTML;

$eloquent = [
    ['name' => 'link_href', 'selector' => 'a', 'attr' => 'href' /*...*/ ],
    ['name' => 'img_src', 'selector' => 'img', 'attr' => 'src' /*...*/ ],
    ['name' => 'link_text', 'selector' => 'a', 'attr' => 'text' /*...*/ ],
]

$data = QueryList::handle(OneAttrPerElementHandler::class)
    ->setHtml($html)
    ->extract($eloquent, 'selector', 'attr', 'name'); // first $arg can be array of obj/array

print_r($data->all());

结果

Array
(
    [0] => Array
        (
            [link_href] => http://querylist.cc
            [img_src] => http://querylist.com/1.jpg
            [link_text] => QueryList Website
        )
    [1] => Array
        (
            [link_href] => http://v3.querylist.cc
            [img_src] => http://querylist.com/2.jpg
            [link_text] => QueryList V3 doc
        )
)

处理器

使用handle()方法向Querylist添加处理器。

// HtmlCharsetHandler is default handler, no need to add manually
// Let HtmlCharsetHandler recover $html from 'UTF-16' to 'UTF-8' before insert
QL::handle(HtmlCharsetHandler::class, 'UTF-16'); 

// Absolute dom urls
QL::handle(AbsoluteUrlsHandler::class, $current_uri);

// Remove continue spaces
QL::handle(MinifyHtmlHandler::class);

// One attribute per element for extract() function
// is usefull for list crawl
QL::handle(OneAttrPerElementHandler::class);

HTTP客户端(GuzzleHttp)

  • 携带Cookie登录GitHub
//Crawl GitHub content
$ql = QueryList::get('https://github.com','param1=testvalue & params2=somevalue',[
  'headers' => [
      // Fill in the cookie from the browser
      'Cookie' => 'SINAGLOBAL=546064; wb_cmtLike_2112031=1; wvr=6;....'
  ]
]);
//echo $ql->getHtml();
$userName = $ql->find('.header-nav-current-user>.css-truncate-target')->text();
echo $userName;
  • 使用Http代理
$urlParams = ['param1' => 'testvalue','params2' => 'somevalue'];
$opts = [
	// Set the http proxy
    'proxy' => 'http://222.141.11.17:8118',
    //Set the timeout time in seconds
    'timeout' => 30,
     // Fake HTTP headers
    'headers' => [
        'Referer' => 'https://querylist.cc/',
        'User-Agent' => 'testing/1.0',
        'Accept'     => 'application/json',
        'X-Foo'      => ['Bar', 'Baz'],
        'Cookie'    => 'abc=111;xxx=222'
    ]
];
$ql->get('http://httpbin.org/get',$urlParams,$opts);
// echo $ql->getHtml();
  • 模拟登录
// Post login
$ql = QueryList::post('http://xxxx.com/login',[
    'username' => 'admin',
    'password' => '123456'
])->get('http://xxx.com/admin');
// Crawl pages that need to be logged in to access
$ql->get('http://xxx.com/admin/page');
//echo $ql->getHtml();

提交表单

登录GitHub

// Get the QueryList instance
$ql = QueryList::getInstance();
// Get the login form
$form = $ql->get('https://github.com/login')->find('form');

// Fill in the GitHub username and password
$form->find('input[name=login]')->val('your github username or email');
$form->find('input[name=password]')->val('your github password');

// Serialize the form data
$fromData = $form->serializeArray();
$postData = [];
foreach ($fromData as $item) {
    $postData[$item['name']] = $item['value'];
}

// Submit the login form
$actionUrl = 'https://github.com'.$form->attr('action');
$ql->post($actionUrl,$postData);
// To determine whether the login is successful
// echo $ql->getHtml();
$userName = $ql->find('.header-nav-current-user>.css-truncate-target')->text();
if($userName)
{
    echo 'Login successful ! Welcome:'.$userName;
}else{
    echo 'Login failed !';
}

绑定函数扩展

自定义myHttp方法的扩展

$ql = QueryList::getInstance();

//Bind a `myHttp` method to the QueryList object
$ql->bind('myHttp',function ($url){
	// $this is the current QueryList object
    $html = file_get_contents($url);
    $this->setHtml($html);
    return $this;
});

// And then you can call by the name of the binding
$data = $ql->myHttp('https://toutiao.io')->find('h3 a')->texts();
print_r($data->all());

或将包到类中,然后绑定

$ql->bind('myHttp',function ($url){
    return new MyHttp($this,$url);
});

插件使用

  • 使用PhantomJS插件爬取JavaScript动态渲染页面
// Set the PhantomJS binary file path during installation
$ql = QueryList::use(PhantomJs::class,'/usr/local/bin/phantomjs');

// Crawl「500px」all picture links
$data = $ql->browser('https://500px.com/editors')->find('img')->attrs('src');
print_r($data->all());

// Use the HTTP proxy
$ql->browser('https://500px.com/editors',false,[
	'--proxy' => '192.168.1.42:8080',
    '--proxy-type' => 'http'
])
  • 使用CURL多线程插件,多线程爬取GitHub趋势
$ql = QueryList::use(CurlMulti::class);
$ql->curlMulti([
    'https://github.com/trending/php',
    'https://github.com/trending/go',
    //.....more urls
])
 // Called if task is success
 ->success(function (QueryList $ql,CurlMulti $curl,$r){
    echo "Current url:{$r['info']['url']} \r\n";
    $data = $ql->find('h3 a')->texts();
    print_r($data->all());
})
 // Task fail callback
->error(function ($errorInfo,CurlMulti $curl){
    echo "Current url:{$errorInfo['info']['url']} \r\n";
    print_r($errorInfo['error']);
})
->start([
	// Maximum number of threads
    'maxThread' => 10,
    // Number of error retries
    'maxTry' => 3,
]);

插件

查看更多QueryList插件和基于QueryList的产品:QueryList社区

贡献

欢迎为QueryList贡献代码。关于贡献插件,请参阅:QueryList插件贡献指南

作者

Jaeger JaegerCode@gmail.com

如果这个库对您有帮助,请说谢谢购买我一杯啤酒 🍺

许可证

QueryList遵循MIT许可证。请参阅LICENSE文件获取更多详细信息。