You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

304 lines
9.1 KiB

2 years ago
  1. <p align="center">
  2. <img width="150" src="logo.png" alt="QueryList">
  3. <br>
  4. <br>
  5. </p>
  6. # QueryList
  7. `QueryList` is a simple, elegant, extensible PHP Web Scraper (crawler/spider) ,based on phpQuery.
  8. [API Documentation](https://github.com/jae-jae/QueryList/wiki)
  9. [中文文档](README-ZH.md)
  10. ## Features
  11. - Have the same CSS3 DOM selector as jQuery
  12. - Have the same DOM manipulation API as jQuery
  13. - Have a generic list crawling program
  14. - Have a strong HTTP request suite, easy to achieve such as: simulated landing, forged browser, HTTP proxy and other complex network requests
  15. - Have a messy code solution
  16. - Have powerful content filtering, you can use the jQuey selector to filter content
  17. - Has a high degree of modular design, scalability and strong
  18. - Have an expressive API
  19. - Has a wealth of plug-ins
  20. Through plug-ins you can easily implement things like:
  21. - Multithreaded crawl
  22. - Crawl JavaScript dynamic rendering page (PhantomJS/headless WebKit)
  23. - Image downloads to local
  24. - Simulate browser behavior such as submitting Form forms
  25. - Web crawler
  26. - .....
  27. ## Requirements
  28. - PHP >= 7.1
  29. ## Installation
  30. By Composer installation:
  31. ```
  32. composer require jaeger/querylist
  33. ```
  34. ## Usage
  35. #### DOM Traversal and Manipulation
  36. - Crawl「GitHub」all picture links
  37. ```php
  38. QueryList::get('https://github.com')->find('img')->attrs('src');
  39. ```
  40. - Crawl Google search results
  41. ```php
  42. $ql = QueryList::get('https://www.google.co.jp/search?q=QueryList');
  43. $ql->find('title')->text(); //The page title
  44. $ql->find('meta[name=keywords]')->content; //The page keywords
  45. $ql->find('h3>a')->texts(); //Get a list of search results titles
  46. $ql->find('h3>a')->attrs('href'); //Get a list of search results links
  47. $ql->find('img')->src; //Gets the link address of the first image
  48. $ql->find('img:eq(1)')->src; //Gets the link address of the second image
  49. $ql->find('img')->eq(2)->src; //Gets the link address of the third image
  50. // Loop all the images
  51. $ql->find('img')->map(function($img){
  52. echo $img->alt; //Print the alt attribute of the image
  53. });
  54. ```
  55. - More usage
  56. ```php
  57. $ql->find('#head')->append('<div>Append content</div>')->find('div')->htmls();
  58. $ql->find('.two')->children('img')->attrs('alt'); // Get the class is the "two" element under all img child nodes
  59. // Loop class is the "two" element under all child nodes
  60. $data = $ql->find('.two')->children()->map(function ($item){
  61. // Use "is" to determine the node type
  62. if($item->is('a')){
  63. return $item->text();
  64. }elseif($item->is('img'))
  65. {
  66. return $item->alt;
  67. }
  68. });
  69. $ql->find('a')->attr('href', 'newVal')->removeClass('className')->html('newHtml')->...
  70. $ql->find('div > p')->add('div > ul')->filter(':has(a)')->find('p:first')->nextAll()->andSelf()->...
  71. $ql->find('div.old')->replaceWith( $ql->find('div.new')->clone())->appendTo('.trash')->prepend('Deleted')->...
  72. ```
  73. #### List crawl
  74. Crawl the title and link of the Google search results list:
  75. ```php
  76. $data = QueryList::get('https://www.google.co.jp/search?q=QueryList')
  77. // Set the crawl rules
  78. ->rules([
  79. 'title'=>array('h3','text'),
  80. 'link'=>array('h3>a','href')
  81. ])
  82. ->query()->getData();
  83. print_r($data->all());
  84. ```
  85. Results:
  86. ```
  87. Array
  88. (
  89. [0] => Array
  90. (
  91. [title] => Angular - QueryList
  92. [link] => https://angular.io/api/core/QueryList
  93. )
  94. [1] => Array
  95. (
  96. [title] => QueryList | @angular/core - Angularリファレンス - Web Creative Park
  97. [link] => http://www.webcreativepark.net/angular/querylist/
  98. )
  99. [2] => Array
  100. (
  101. [title] => QueryListにQueryを追加したり、追加されたことを感知する | TIPS ...
  102. [link] => http://www.webcreativepark.net/angular/querylist_query_add_subscribe/
  103. )
  104. //...
  105. )
  106. ```
  107. #### Encode convert
  108. ```php
  109. // Out charset :UTF-8
  110. // In charset :GB2312
  111. QueryList::get('https://top.etao.com')->encoding('UTF-8','GB2312')->find('a')->texts();
  112. // Out charset:UTF-8
  113. // In charset:Automatic Identification
  114. QueryList::get('https://top.etao.com')->encoding('UTF-8')->find('a')->texts();
  115. ```
  116. #### HTTP Client (GuzzleHttp)
  117. - Carry cookie login GitHub
  118. ```php
  119. //Crawl GitHub content
  120. $ql = QueryList::get('https://github.com','param1=testvalue & params2=somevalue',[
  121. 'headers' => [
  122. // Fill in the cookie from the browser
  123. 'Cookie' => 'SINAGLOBAL=546064; wb_cmtLike_2112031=1; wvr=6;....'
  124. ]
  125. ]);
  126. //echo $ql->getHtml();
  127. $userName = $ql->find('.header-nav-current-user>.css-truncate-target')->text();
  128. echo $userName;
  129. ```
  130. - Use the Http proxy
  131. ```php
  132. $urlParams = ['param1' => 'testvalue','params2' => 'somevalue'];
  133. $opts = [
  134. // Set the http proxy
  135. 'proxy' => 'http://222.141.11.17:8118',
  136. //Set the timeout time in seconds
  137. 'timeout' => 30,
  138. // Fake HTTP headers
  139. 'headers' => [
  140. 'Referer' => 'https://querylist.cc/',
  141. 'User-Agent' => 'testing/1.0',
  142. 'Accept' => 'application/json',
  143. 'X-Foo' => ['Bar', 'Baz'],
  144. 'Cookie' => 'abc=111;xxx=222'
  145. ]
  146. ];
  147. $ql->get('http://httpbin.org/get',$urlParams,$opts);
  148. // echo $ql->getHtml();
  149. ```
  150. - Analog login
  151. ```php
  152. // Post login
  153. $ql = QueryList::post('http://xxxx.com/login',[
  154. 'username' => 'admin',
  155. 'password' => '123456'
  156. ])->get('http://xxx.com/admin');
  157. // Crawl pages that need to be logged in to access
  158. $ql->get('http://xxx.com/admin/page');
  159. //echo $ql->getHtml();
  160. ```
  161. #### Submit forms
  162. Login GitHub
  163. ```php
  164. // Get the QueryList instance
  165. $ql = QueryList::getInstance();
  166. // Get the login form
  167. $form = $ql->get('https://github.com/login')->find('form');
  168. // Fill in the GitHub username and password
  169. $form->find('input[name=login]')->val('your github username or email');
  170. $form->find('input[name=password]')->val('your github password');
  171. // Serialize the form data
  172. $fromData = $form->serializeArray();
  173. $postData = [];
  174. foreach ($fromData as $item) {
  175. $postData[$item['name']] = $item['value'];
  176. }
  177. // Submit the login form
  178. $actionUrl = 'https://github.com'.$form->attr('action');
  179. $ql->post($actionUrl,$postData);
  180. // To determine whether the login is successful
  181. // echo $ql->getHtml();
  182. $userName = $ql->find('.header-nav-current-user>.css-truncate-target')->text();
  183. if($userName)
  184. {
  185. echo 'Login successful ! Welcome:'.$userName;
  186. }else{
  187. echo 'Login failed !';
  188. }
  189. ```
  190. #### Bind function extension
  191. Customize the extension of a `myHttp` method:
  192. ```php
  193. $ql = QueryList::getInstance();
  194. //Bind a `myHttp` method to the QueryList object
  195. $ql->bind('myHttp',function ($url){
  196. // $this is the current QueryList object
  197. $html = file_get_contents($url);
  198. $this->setHtml($html);
  199. return $this;
  200. });
  201. // And then you can call by the name of the binding
  202. $data = $ql->myHttp('https://toutiao.io')->find('h3 a')->texts();
  203. print_r($data->all());
  204. ```
  205. Or package to class, and then bind:
  206. ```php
  207. $ql->bind('myHttp',function ($url){
  208. return new MyHttp($this,$url);
  209. });
  210. ```
  211. #### Plugin used
  212. - Use the PhantomJS plugin to crawl JavaScript dynamically rendered pages:
  213. ```php
  214. // Set the PhantomJS binary file path during installation
  215. $ql = QueryList::use(PhantomJs::class,'/usr/local/bin/phantomjs');
  216. // Crawl「500px」all picture links
  217. $data = $ql->browser('https://500px.com/editors')->find('img')->attrs('src');
  218. print_r($data->all());
  219. // Use the HTTP proxy
  220. $ql->browser('https://500px.com/editors',false,[
  221. '--proxy' => '192.168.1.42:8080',
  222. '--proxy-type' => 'http'
  223. ])
  224. ```
  225. - Using the CURL multithreading plug-in, multi-threaded crawling GitHub trending :
  226. ```php
  227. $ql = QueryList::use(CurlMulti::class);
  228. $ql->curlMulti([
  229. 'https://github.com/trending/php',
  230. 'https://github.com/trending/go',
  231. //.....more urls
  232. ])
  233. // Called if task is success
  234. ->success(function (QueryList $ql,CurlMulti $curl,$r){
  235. echo "Current url:{$r['info']['url']} \r\n";
  236. $data = $ql->find('h3 a')->texts();
  237. print_r($data->all());
  238. })
  239. // Task fail callback
  240. ->error(function ($errorInfo,CurlMulti $curl){
  241. echo "Current url:{$errorInfo['info']['url']} \r\n";
  242. print_r($errorInfo['error']);
  243. })
  244. ->start([
  245. // Maximum number of threads
  246. 'maxThread' => 10,
  247. // Number of error retries
  248. 'maxTry' => 3,
  249. ]);
  250. ```
  251. ## Plugins
  252. - [jae-jae/QueryList-PhantomJS](https://github.com/jae-jae/QueryList-PhantomJS):Use PhantomJS to crawl Javascript dynamically rendered page.
  253. - [jae-jae/QueryList-CurlMulti](https://github.com/jae-jae/QueryList-CurlMulti) : Curl multi threading.
  254. - [jae-jae/QueryList-AbsoluteUrl](https://github.com/jae-jae/QueryList-AbsoluteUrl) : Converting relative urls to absolute.
  255. - [jae-jae/QueryList-Rule-Google](https://github.com/jae-jae/QueryList-Rule-Google) : Google searcher.
  256. - [jae-jae/QueryList-Rule-Baidu](https://github.com/jae-jae/QueryList-Rule-Baidu) : Baidu searcher.
  257. View more QueryList plugins and QueryList-based products: [QueryList Community](https://github.com/jae-jae/QueryList-Community)
  258. ## Contributing
  259. Welcome to contribute code for the QueryList。About Contributing Plugins can be viewed:[QueryList Plugin Contributing Guide](https://github.com/jae-jae/QueryList-Community/blob/master/CONTRIBUTING.md)
  260. ## Author
  261. Jaeger <JaegerCode@gmail.com>
  262. If this library is useful for you, say thanks [buying me a beer :beer:](https://www.paypal.me/jaepay)!
  263. ## Lisence
  264. QueryList is licensed under the license of MIT. See the LICENSE for more details.