【问题标题】:Bing search API and Azure必应搜索 API 和 Azure
【发布时间】:2012-06-06 08:26:09
【问题描述】:

我正在尝试以编程方式在 Microsoft Bing 搜索引擎上执行搜索。

这是我的理解:

  • 有一个 Bing Search API 2.0 ,很快将被替换(2012 年 8 月 1 日)
  • 新的 API 称为 Windows Azure Marketplace。
  • 您对两者使用不同的 URL。

在旧 API (Bing Search API 2.0)中,您在 URL 中指定一个密钥(应用程序 ID),该密钥将用于验证请求。只要在URL中有key作为参数,就可以获得结果。

在新的 API (Windows Azure Marketplace) 中,您不会在 URL 中包含密钥(帐户密钥)。相反,您输入一个查询 URL,然后服务器将询问您的凭据。使用浏览器时,会有一个弹窗要求输入账户名和密码。说明是将帐户名留空,然后在密码字段中插入您的密钥。

好的,我已经完成了所有这些,我可以在浏览器页面上看到 JSON 格式的搜索结果。

如何在 PHP 中以编程方式执行此操作?我尝试从 Microsoft MSDN 库中搜索文档和示例代码,但是我搜索的地方有误,或者那里的资源极其有限。

谁能告诉我你如何在 PHP 中执行“在弹出窗口的密码字段中输入密钥”部分?

非常感谢。

【问题讨论】:

  • 那么通过 Azure 翻译 api 呢?任何提示链接我都会非常感激。

标签: php search bing


【解决方案1】:

新服务的文档可能会变得有点有趣——尤其是在 MSDN 的rabbit-warren 中。我能在Migration Guide 这个Bing Search API 页面上找到最清楚的解释。最重要的是,迁移指南最后有一个很好的简单 PHP 示例。

编辑:好的,迁移指南是一个起点,但它不是最好的例子。以下是对我有用的两种方法(无代理、防火墙等干扰):

使用 file_get_contents

注意:需要启用“allow_url_fopen”才能使其正常工作。如果不是,您可以使用ini_set(或更改 php.ini 等)。

if (isset($_POST['submit'])) 
{

    // Replace this value with your account key
    $accountKey = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=';            
    $ServiceRootURL =  'https://api.datamarket.azure.com/Bing/Search/';                    
    $WebSearchURL = $ServiceRootURL . 'Web?$format=json&Query=';

    $cred = sprintf('Authorization: Basic %s', 
      base64_encode($accountKey . ":" . $accountKey) );

    $context = stream_context_create(array(
        'http' => array(
            'header'  => $cred
        )
    ));

    $request = $WebSearchURL . urlencode( '\'' . $_POST["searchText"] . '\'');

    $response = file_get_contents($request, 0, $context);

    $jsonobj = json_decode($response);

    echo('<ul ID="resultList">');

    foreach($jsonobj->d->results as $value)
    {                        
        echo('<li class="resultlistitem"><a href="' 
                . $value->URL . '">'.$value->Title.'</a>');
    }

    echo("</ul>");
}

使用 cURL

如果安装了cURL,这几天很正常:

<?php
  $query = $_POST['searchText'];

  $accountKey = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
  $serviceRootURL =  'https://api.datamarket.azure.com/Bing/Search/';  
  $webSearchURL = $serviceRootURL . 'Web?$format=json&Query=';

  $request = $webSearchURL . "%27" . urlencode( "$query" ) . "%27";

  $process = curl_init($request);
  curl_setopt($process, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  curl_setopt($process, CURLOPT_USERPWD,  "$accountKey:$accountKey");
  curl_setopt($process, CURLOPT_TIMEOUT, 30);
  curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
  $response = curl_exec($process);
  $response = json_decode($response);

  echo "<ol>";
  foreach( $response->d->results as $result ) {
    $url = $result->Url;
    $title = $result->Title;

    echo "<li><a href='$url'>$title</a></li>";
  }
  echo "</ol>";
?>

[WTS] 将 SearchWeb 更改为 Search。

【讨论】:

  • 或者你可以看看curl而不是file_get_contents。
  • 它本质上是正确的,但作为一个例子,它可以被简化。我在答案中添加了两种方法。
  • 看来作者提出了一个新问题并自己回答了:stackoverflow.com/q/10845672/628267gg
  • 一目了然,您需要将$serviceRootURL 更改为https://api.datamarket.azure.com/Bing/Search/$webSearchURLImage?$format=json&amp;Query= 结尾。如果您需要更多信息,我建议您发布一个新问题。
  • /Bing/SearchWeb/ 应该是 /Bing/Search/ -- 这对我有用
【解决方案2】:

别忘了把这个:

base64_encode("ignored:".$accountKey)

代替:

base64_encode($accountKey . ":" . $accountKey)

【讨论】:

  • 从我的测试来看,两者都有效,但我知道这可能因系统而异。
【解决方案3】:

以上都不适合我。我正在运行 MAMP,这可能是相关的。试试下面的:


$accountKey = '=';


function sitesearch ($query, $site, $accountKey, $count=NULL){
  // code from http://go.microsoft.com/fwlink/?LinkID=248077

    $context = stream_context_create(array(
    'http' => array(
      'request_fulluri' => true,       
      'header'  => "Authorization: Basic " . base64_encode($accountKey . ":" . $accountKey)
    ) 
    )); 

    $ServiceRootURL =  'https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/News?Market=%27en-GB%27&';
    $WebSearchURL = $ServiceRootURL . '$format=json&Query=';  

    $request = $WebSearchURL . urlencode("'$query'"); // note the extra single quotes
    if ($count) $request .= "&\$top=$count"; // note the dollar sign before $top--it's not a variable!
    return json_decode(file_get_contents($request, 0, $context), true);
}


$q = "query";

if ($q){
  // get search results
  $articles = sitesearch ($q, $_SERVER['HTTP_HOST'], $accountKey , 100);

  foreach($articles['d']['results'] as $article) {
      echo " <p>".$article['Title'].'</p>';
      echo " <p>".$article['Description'].'</p>';
      echo " <p>".$article['Source'].'</p>';
      echo " <p>".strtotime($article['Date']).'</p>';
  }



}

来自: http://bililite.com/blog/2012/06/05/new-bing-api/

【讨论】:

  • 注意源设置为News,这里是$ServiceRootURL = 'https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/News?Market=%27en-GB%27&amp;';
【解决方案4】:

这是一个搜索 API 的工作示例,只需将“XXXX”替换为您的访问密钥。即使我浪费了好几个小时试图让它使用 cURL 工作,但由于本地的“CURLOPT_SSL_VERIFYPEER”而失败:( - 所以请确保你的 cURL 选项设置正确。

$url = 'https://api.datamarket.azure.com/Bing/Search/Web?Query=%27xbox%27';
$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($process, CURLOPT_USERPWD, base64_encode("username:XXXX"));
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($process);

# Deliver
return $response;

# Have a great day!
curl_close($process);

【讨论】:

  • 这行得通!,这里的关键是“用户名:密钥”应该是基本身份验证标头中的 base 64 编码,而不仅仅是“密钥”:)
【解决方案5】:

以下是如何使用Unirest library 调用 Bing/Azure API 的示例。

require_once '/path/to/unirest-php/lib/Unirest.php';

$accountKey = "xxx";
$searchResults = Unirest::get("https://api.datamarket.azure.com/Bing/Search/v1/Composite",
    array(),
    array(
        'Query' => '%27Microsoft%27',
        'Sources' => '%27web%2Bimage%2Bvideo%2Bnews%2Bspell%27',
        '$format' => 'json',
    ), $accountKey, $accountKey
);

// Results are here:
$objectArray = $searchResults->body->d->results;
$rawJson = $searchResults->raw_body;

您可以通过在 URL 中定义 Source 参数来省略它:https://api.datamarket.azure.com/Bing/Search/v1/Webhttps://api.datamarket.azure.com/Bing/Search/v1/Image

注意:请求 URL 中的参数区分大小写。对于 Bing,它们以大写字母开头。

【讨论】:

    【解决方案6】:

    http://www.guguncube.com/2771/python-using-the-bing-search-api

    它包含查询 bing 的 python 代码,这是根据最新的新 API (Windows Azure Marketplace)

    # -*- coding: utf-8 -*-
    import urllib
    import urllib2
    import json
    
    def main():
        query = "sunshine"
        print bing_search(query, 'Web')
        print bing_search(query, 'Image')
    
    def bing_search(query, search_type):
        #search_type: Web, Image, News, Video
        key= 'YOUR_API_KEY'
        query = urllib.quote(query)
        # create credential for authentication
        user_agent = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; FDM; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 1.1.4322)'
        credentials = (':%s' % key).encode('base64')[:-1]
        auth = 'Basic %s' % credentials
        url = 'https://api.datamarket.azure.com/Data.ashx/Bing/Search/'+search_type+'?Query=%27'+query+'%27&$top=5&$format=json'
        request = urllib2.Request(url)
        request.add_header('Authorization', auth)
        request.add_header('User-Agent', user_agent)
        request_opener = urllib2.build_opener()
        response = request_opener.open(request) 
        response_data = response.read()
        json_result = json.loads(response_data)
        result_list = json_result['d']['results']
        print result_list
        return result_list
    
    if __name__ == "__main__":
        main()
    

    【讨论】:

    • 你应该复制/粘贴代码而不是仅仅链接它,以防它消失或将来被移动
    • 非常感谢您添加 python 代码。 Azure 文档链接给出了 404 :) 所以它有很大帮助。你知道他在 django_pipes 项目中的工作是怎么做到的吗..
    【解决方案7】:

    您可以使用下面的代码来获取必应搜索结果

    $acctKey = 'Your account key here';
    $rootUri = 'https://api.datamarket.azure.com/Bing/Search';
    $query = 'Kitchen';
    $serviceOp ='Image';
    $market ='en-us';
    $query = urlencode("'$query'");
    $market = urlencode("'$market'");
    $requestUri = "$rootUri/$serviceOp?\$format=json&Query=$query&Market=$market";
    $auth = base64_encode("$acctKey:$acctKey");
    $data = array(  
                'http' => array(
                            'request_fulluri' => true,
                            'ignore_errors' => true,
                            'header' => "Authorization: Basic $auth"
                            )
                );
    $context = stream_context_create($data);
    $response = file_get_contents($requestUri, 0, $context);
    $response=json_decode($response);
    echo "<pre>";
    print_r($response);
    echo "</pre>";
    

    【讨论】:

    • 谢谢。终于有人为这个 API 带来了一丝理智。我的猜测是,之前的所有响应都在某个时间点起作用,但微软一直在改变。
    • 这个有用 ;) 感谢分享,bing sux 上的文档。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多