ppajer / searchresults
获取搜索结果页面的便捷方式,可用于进一步处理。目前仅支持Google,未来将可扩展。
dev-master
2020-08-05 13:44 UTC
Requires
This package is auto-updated.
Last update: 2024-09-05 22:57:41 UTC
README
获取搜索结果页面的便捷方式,可用于进一步处理。目前仅支持Google,未来将可扩展。
需求
- PHP7+
- WebScraper(Composer包的一部分)
- DOM Extractor(包含在WebScraper中)
- Request(包含在WebScraper中)
安装
通过Composer安装或本地下载仓库。注意:此包需要WebScraper才能运行,因此如果手动安装,您需要手动包含scraper及其依赖项(DOM Extractor和Request)。
方法和属性
class SearchResults {
public $query : String // The search term for the results
public $limit : Int // The number of pages to fetch. Default: 1
public $location : String|null // A canonical location name.
public $results : Array // The search results.
public function __construct__(Array $args) : // Where $args is an Array with 'query', 'limit' and 'location' as possible keys.
public function get() : Array<Array> // Returns the results
public static function getMultiple(Array $args) : Array<SearchResults> // Returns an array of SearchResult objects
public static function autocompleteSearchLocation(String $query) : Array<String> // Returns an array of search locations
}
用法
只需包含所需的文件,并将搜索选项提供给构造函数。这些包括:query
、limit
和location
。
require 'Webscraper.php';
require 'SearchResults.php';
$search = [
'query' => 'Budapest', // The query to search
'limit' => 3 // Number of pages fetched
'location' => 'New York, United States' // The location to show searches from
];
$serps = new SearchResults($search);
foreach ($serps as $position => $result) {
echo "Result URL #$position:".$result['link'];
}
多个关键词
您还可以使用getMultiple()
方法查询关键词数组。它接受与构造函数预期相似的数组数组。
$multipleWithLimits = [
[
'query' => 'Budapest',
'limit' => 5
],
[
'query' => 'Sopron',
'limit' => 2,
'location' => 'London, United Kingdom'
]
];
$results = SearchResults::getMultiple($multipleWithLimits);
// Returns an array of SearchResult objects
// Results will have 5 and 2 pages respectively, from different locations.
位置支持
库包含Google支持的所有规范名称列表。您可以使用此列表来查找您感兴趣的地点的规范名称。该列表相当大(74000项),因此为用户提供自动完成功能非常有用。您可以通过使用您选择的任何前端解决方案,并结合后端的autocompleteSearchLocation()
方法来实现。
为了提高搜索速度并减少内存使用,还提供了一个简化的列表 - 这是以降低精度为代价来减少大小,仅包含200个条目,应该适合大多数低精度位置需求。只需将可选参数传递给自动完成方法以获取简化列表即可。
// This will listen to requests containing the q parameter and automatically return it to the browser
SearchResults::autocompleteSearchLocation();
// This does the same thing, but searched from the simplified list for improved speed
SearchResults::autocompleteSearchLocation(true);