Baidu.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. const API = 'https://www.baidu.com/s';
  17. const RULES = [
  18. 'title' => ['h3','text'],
  19. 'link' => ['h3>a','href']
  20. ];
  21. const RANGE = '.result';
  22. public function __construct(QueryList $ql, $pageNumber)
  23. {
  24. $this->ql = $ql->rules(self::RULES)->range(self::RANGE);
  25. $this->pageNumber = $pageNumber;
  26. }
  27. public static function install(QueryList $queryList, ...$opt)
  28. {
  29. $name = $opt[0] ?? 'baidu';
  30. $queryList->bind($name,function ($pageNumber = 10){
  31. return new Baidu($this,$pageNumber);
  32. });
  33. }
  34. public function search($keyword)
  35. {
  36. $this->keyword = $keyword;
  37. return $this;
  38. }
  39. public function page($page = 1,$realURL = false)
  40. {
  41. return $this->query($page)->query()->getData(function ($item) use($realURL){
  42. $realURL && $item['link'] = $this->getRealURL($item['link']);
  43. return $item;
  44. });
  45. }
  46. public function getCount()
  47. {
  48. $count = 0;
  49. $text = $this->query(1)->find('.nums')->text();
  50. if(preg_match('/[\d,]+/',$text,$arr))
  51. {
  52. $count = str_replace(',','',$arr[0]);
  53. }
  54. return (int)$count;
  55. }
  56. public function getCountPage()
  57. {
  58. $count = $this->getCount();
  59. $countPage = ceil($count / $this->pageNumber);
  60. return $countPage;
  61. }
  62. protected function query($page = 1)
  63. {
  64. $this->ql->get(self::API,[
  65. 'wd' => $this->keyword,
  66. 'rn' => $this->pageNumber,
  67. 'pn' => $this->pageNumber * ($page-1)
  68. ]);
  69. return $this->ql;
  70. }
  71. protected function getRealURL($url)
  72. {
  73. //得到百度跳转的真正地址
  74. $header = get_headers($url,1);
  75. if (strpos($header[0],'301') || strpos($header[0],'302'))
  76. {
  77. if(is_array($header['Location']))
  78. {
  79. //return $header['Location'][count($header['Location'])-1];
  80. return $header['Location'][0];
  81. }
  82. else
  83. {
  84. return $header['Location'];
  85. }
  86. }
  87. else
  88. {
  89. return $url;
  90. }
  91. }
  92. }