替换url中的变量以进行bing搜索

时间:2013-08-11 16:21:23

标签: python

我有一个代码可以从bing搜索中获取网址。

import requests
URL = "https://mykey:mykey@api.datamarket.azure.com/Bing/Search/Web?$format=json&Query='query'"
API_KEY = 'mykey'
query = "JohnDalton"
def request(query, **params):
    query = ('%27'+query+ '%27')
    r = requests.get(URL % {'query': query}, auth=('', API_KEY))
    print r.content
    return r.json()['d']['results']


r = request("JohnDalton")

print r[0]['Url']

该脚本只获取与我在网址中放入的“查询”相关的网址,即使我已尝试将该值替换为该行中的可修改查询;

r = requests.get(URL % {'query': query}, auth=('', API_KEY))

为什么不替换值?

3 个答案:

答案 0 :(得分:1)

该字符串格式代码无效。 试试这个:

URL = "https://mykey:mykey@api.datamarket.azure.com/Bing/Search/Web?$format=json&Query=%s"
get(URL % urllib.quote(query, safe='~()*!.\'')) # Don't forget to urlencode it

答案 1 :(得分:1)

您需要更改格式字符串以使用%(query)s来替换内容。请参阅以下内容 -

>>> 'My name is %(name)s' % {'name': 'Monty Python'}
'My name is Monty Python'

或者使用format(...)如下 -

>>> 'My name is {name}'.format(name='Monty Python')
'My name is Monty Python'

答案 2 :(得分:1)

不要自己构建网址 - requests can handle it

API_KEY = 'mykey'
def request(query):
    # quotes are for whole-phrase matching - don't escape them here
    query = '"'+query+ '"'

    # let requests build your URL
    r = requests.get(
        'https://mykey:mykey@api.datamarket.azure.com/Bing/Search/Web',
        params={'$format': 'json', 'Query': query},
        auth=('', API_KEY)
    )

    print r.content
    return r.json()['d']['results']