Google.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Jaeger <JaegerCode@gmail.com>
  5. * Date: 2017/10/1
  6. * Baidu searcher
  7. */
  8. namespace QL\Ext;
  9. use QL\Contracts\PluginContract;
  10. use QL\QueryList;
  11. class Google implements PluginContract
  12. {
  13. protected $ql;
  14. protected $keyword;
  15. protected $pageNumber = 10;
  16. protected $httpOpt = [];
  17. const API = 'https://www.google.co.jp/search';
  18. const RULES = [
  19. 'title' => ['h3','text'],
  20. 'link' => ['h3>a','href']
  21. ];
  22. const RANGE = '.g';
  23. public function __construct(QueryList $ql, $pageNumber)
  24. {
  25. $this->ql = $ql->rules(self::RULES)->range(self::RANGE);
  26. $this->pageNumber = $pageNumber;
  27. }
  28. public static function install(QueryList $queryList, ...$opt)
  29. {
  30. $name = $opt[0] ?? 'google';
  31. $queryList->bind($name,function ($pageNumber = 10){
  32. return new Google($this,$pageNumber);
  33. });
  34. }
  35. public function setHttpOpt(array $httpOpt = [])
  36. {
  37. $this->httpOpt = $httpOpt;
  38. return $this;
  39. }
  40. public function search($keyword)
  41. {
  42. $this->keyword = $keyword;
  43. return $this;
  44. }
  45. public function page($page = 1)
  46. {
  47. return $this->query($page)->query()->getData();
  48. }
  49. public function getCount()
  50. {
  51. $count = 0;
  52. $text = $this->query(1)->find('#resultStats')->text();
  53. if(preg_match('/[\d,]+/',$text,$arr))
  54. {
  55. $count = str_replace(',','',$arr[0]);
  56. }
  57. return (int)$count;
  58. }
  59. public function getCountPage()
  60. {
  61. $count = $this->getCount();
  62. $countPage = ceil($count / $this->pageNumber);
  63. return $countPage;
  64. }
  65. protected function query($page = 1)
  66. {
  67. $this->ql->get(self::API,[
  68. 'q' => $this->keyword,
  69. 'num' => $this->pageNumber,
  70. 'start' => $this->pageNumber * ($page-1)
  71. ],$this->httpOpt);
  72. return $this->ql;
  73. }
  74. }