当我想自定义需要"id"的url令牌时,我得到了一个TypeError: cannot concatenate 'str' and 'int' objects
。
代替由单个id返回的单个结果(例如303),我想要从另一个url检索的变量"station"中声明的所有id的结果。代码如下:
import urllib2
import json
#assign the url
url="http://ewodr.wodr.poznan.pl/doradztwo/swd/swd_api.php?dane={%22token%22:%22pcss%22,%22operacja%22:%22stacje%22}"
# open the url
json_obj= urllib2.urlopen(str(url))
output= json.load(json_obj)
station_res= output ['data'] ['features']
for item in station_res:
station= item['id']
url1="http://ewodr.wodr.poznan.pl/doradztwo/swd/meteo_api.php?dane={%22token%22:%22pcss%22,%22id%22:}" +str(station)
json_obj2= urllib2.urlopen(str(url1))
output2= json.load(json_obj2)
for item2 in output2 ['data']:
print item2
现在我试着把"stations"作为字符串放在"url1"中,但它仍然不能识别url并返回一个错误:
Traceback (most recent call last):
`File "stations.py", line 23, in <module>`
`for item2 in output2 ['data']:`
KeyError: 'data'
问题是你在'}'之后添加了id
,所以你的URL看起来像
http://ewodr.wodr.poznan.pl/doradztwo/swd/meteo_api.php?dane={%22token%22:%22pcss%22,%22id%22:}331
应该是
http://ewodr.wodr.poznan.pl/doradztwo/swd/meteo_api.php?dane={%22token%22:%22pcss%22,%22id%22:331}
所以我建议:
url1 = 'http://ewodr.wodr.poznan.pl/doradztwo/swd/meteo_api.php?dane={%22token%22:%22pcss%22,%22id%22:' + str(station) + '}'
,你不需要写str(url1)
,因为它已经是字符串。