2

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

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']

该脚本仅获取与我放入 url 的“查询”相关的 url,即使我尝试用行中的可变查询替换该值;

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

为什么它不替换值?

4

3 回答 3

1

不要自己构建网址 -requests可以处理它

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']
于 2013-08-11T17:27:56.473 回答
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
于 2013-08-11T16:29:59.090 回答
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'
于 2013-08-11T16:30:45.770 回答