Baidu.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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 Baidu implements PluginContract
  12. {
  13. protected $ql;
  14. protected $keyword;
  15. protected $pageNumber = 10;
  16. protected $httpOpt = [];
  17. const API = 'https://www.baidu.com/s';
  18. const RULES = [
  19. 'title' => ['h3','text'],
  20. 'link' => ['h3>a','href']
  21. ];
  22. const RANGE = '.result';
  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] ?? 'baidu';
  31. $queryList->bind($name,function ($pageNumber = 10){
  32. return new Baidu($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,$realURL = false)
  46. {
  47. return $this->query($page)->query()->getData(function ($item) use($realURL){
  48. $realURL && $item['link'] = $this->getRealURL($item['link']);
  49. return $item;
  50. });
  51. }
  52. public function getCount()
  53. {
  54. $count = 0;
  55. $text = $this->query(1)->find('.nums')->text();
  56. if(preg_match('/[\d,]+/',$text,$arr))
  57. {
  58. $count = str_replace(',','',$arr[0]);
  59. }
  60. return (int)$count;
  61. }
  62. public function getCountPage()
  63. {
  64. $count = $this->getCount();
  65. $countPage = ceil($count / $this->pageNumber);
  66. return $countPage;
  67. }
  68. protected function query($page = 1)
  69. {
  70. $this->ql->get(self::API,[
  71. 'wd' => $this->keyword,
  72. 'rn' => $this->pageNumber,
  73. 'pn' => $this->pageNumber * ($page-1)
  74. ],$this->httpOpt);
  75. return $this->ql;
  76. }
  77. protected function getRealURL($url)
  78. {
  79. //得到百度跳转的真正地址
  80. $header = get_headers($url,1);
  81. if (strpos($header[0],'301') || strpos($header[0],'302'))
  82. {
  83. if(is_array($header['Location']))
  84. {
  85. //return $header['Location'][count($header['Location'])-1];
  86. return $header['Location'][0];
  87. }
  88. else
  89. {
  90. return $header['Location'];
  91. }
  92. }
  93. else
  94. {
  95. return $url;
  96. }
  97. }
  98. }