必应搜索API和Azure

27

我正在尝试在微软必应搜索引擎上进行编程搜索。

以下是我的理解:

  • Bing Search API 2.0曾经存在,但将很快被取代(2012年8月1日)。
  • 新API称为Windows Azure Marketplace。
  • 您需要使用不同的URL来访问它们。

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

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

好的,我已经做到了,并且我可以在浏览器页面上看到我的搜索的JSON格式结果。

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

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

非常感谢您的帮助。


Azure上的翻译API怎么样?有什么提示或链接可以提供吗?非常感谢。 - Petr Velký
7个回答

37

在MSDN的兔子洞里,新服务的文档可能会变得有点有趣。我能找到的最清晰的解释在迁移指南中,该指南来自于必应搜索 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。


2
你也可以看一下curl,而不是使用file_get_contents。 - John C
1
本质上是正确的,但作为一个例子,它可以被简化。我在我的答案中添加了两种方法。 - John C
1
似乎作者自己提出了一个新问题并回答了它:http://stackoverflow.com/q/10845672/628267 gg - John C
1
一眼看去,您需要将$serviceRootURL更改为https://api.datamarket.azure.com/Bing/Search/,并将$webSearchURL结尾添加Image?$format=json&Query=。如果您需要更多信息,建议发布一个新问题。 - John C
1
/Bing/SearchWeb/ 应该改为 /Bing/Search/ -- 这样对我来说可以正常工作。 - Kristopher Windsor
显示剩余4条评论

6

以上方法对我都没用。我是在运行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>';
  }



}

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


请注意,此处源设置为“新闻”,其中 $ServiceRootURL = 'https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/News?Market=%27en-GB%27&'; - Fallen

5
您可以使用以下代码获取Bing搜索结果。
$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带来了一丝理智。我猜以前的所有回复在某个时候都是有效的,但微软不断地更改东西。 - Nate Bunney
这个可以用 ;) 谢谢分享,bing 的文档太烂了。 - Sagive

4

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

这篇文章包含了使用Python代码查询Bing搜索引擎的方法,而且是根据最新的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()

你应该复制/粘贴代码,而不仅仅是链接它,以防将来它消失或被移动。 - AlexB
非常感谢您添加Python代码。Azure文档链接出现404错误,所以这对我帮助很大。您有没有想过如何将其与django_pipes项目一起使用? - pranshus

3

不要忘记添加这个:

base64_encode("ignored:".$accountKey)

改为:

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

从我的测试来看,两种方法都可以,但我理解这可能因系统而异。 - John C

3

这是一个可用的Search 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);

1
这个可行!关键在于“用户名:密钥”应该在基本身份验证标头中进行base64编码,而不仅仅是“密钥” :) - Rajiev Timal

1
以下是如何使用Unirest库调用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,它们以大写字母开头。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接