requests.get超时,在浏览器中立即返回的url

时间:2017-01-31 10:04:21

标签: python python-requests

当网址在浏览器中工作时,会导致request.get超时的原因是什么?

我已经在requests.get returns 403 while the same url works in browser看到了关于屏蔽用户代理的回复,但我的问题是我得到了一个TimeoutError,而不是它被禁止。无论如何我试过了,它没有帮助。

import requests

def onemap_geocode(postalcode):
    header = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
    onemap_request = 'https://developers.onemap.sg/commonapi/search?searchVal=' + str(postalcode) + '&returnGeom=Y&getAddrDetails=N'
    print(onemap_request)
    response = requests.get(onemap_request,headers=header)
    print('response obtained')
    response_json = response.json
    lat = response_json['results'][0]['LATITUDE']
    lon = response_json['results'][0]['LONGITUDE']

    return lat + ', ' + lon

onemap_geocode(178880)

2 个答案:

答案 0 :(得分:0)

在超时时使用大号:

response = requests.get(onemap_request,headers=header,timeout=100)

答案 1 :(得分:0)

response_json = response.json

调用response.json方法时缺少括号。此行应更改为response_json = response.json()

除此之外,您的代码按预期工作。