使用Bing搜索视频的Python程序
我一直在尝试使用必应搜索引擎来搜索视频。但是每次尝试时,我都会遇到一个错误,提示HTTPError:HTTPError 403:Forbidden。
import urllib
import urllib2
import json
def main():
query = "'pyscripter'"
print bing_search(query, 'Video')
def bing_search(query, search_type):
#search_type: Web, Image, News, Video
key= 'LsE7jElMmTDfbrnCEmrCmCEBbaPxMG5BvKr9CsfmSNS'
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()
错误信息是:
Traceback (most recent call last):
File "<module1>", line 30, in <module>
File "<module1>", line 7, in main
File "<module1>", line 22, in bing_search
File "C:\Python27\lib\urllib2.py", line 410, in open
response = meth(req, response)
File "C:\Python27\lib\urllib2.py", line 523, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python27\lib\urllib2.py", line 448, in error
return self._call_chain(*args)
File "C:\Python27\lib\urllib2.py", line 382, in _call_chain
result = func(*args)
File "C:\Python27\lib\urllib2.py", line 531, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 403: Forbidden
在尝试这个之前,我使用过YouTube的搜索API,那个是可以正常工作的。但唯一的问题是,它只能找到YouTube数据库里的视频。我想要的是与某个关键词相关的所有视频的链接,这些视频可能在互联网上的任何地方。所以我开始使用必应搜索引擎。如果有人能提供帮助,我将非常感激。
1 个回答
0
我遇到了保存的问题。
当你请求一个网页或资源时,网络服务器可能会返回一个403禁止访问的状态码。这意味着服务器可以被访问,并且理解了你的请求,但就是不愿意执行任何操作。出现403状态码的原因是服务器被设置为拒绝访问客户端请求的资源,可能是出于某种原因。
在我的情况下,我忘记激活“必应搜索”的订阅,所以我需要去“https://datamarket.azure.com/dataset/bing/search”激活“必应搜索”的订阅。