2016-11-10 23 views
0

当我想自定义需要“id”的url标记时,我得到一个TypeError: cannot concatenate 'str' and 'int' objects如何使用python脚本中的已定义变量自定义PHP url标记?

代替一个单一的id(比如说303)返回的单个结果,我希望得到所有在变量“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: 
 
\t station= item['id'] 
 
url1="http://ewodr.wodr.poznan.pl/doradztwo/swd/meteo_api.php?dane={%22token%22:%22pcss%22,%22id%22:}" +str(station) 
 
\t json_obj2= urllib2.urlopen(str(url1)) 
 
\t output2= json.load(json_obj2) 
 
\t for item2 in output2 ['data']: 
 
\t \t print item2

我试图把“站”作为“URL1”的字符串,但它仍然无法识别URL并返回一个错误:

Traceback (most recent call last): 
    `File "stations.py", line 23, in <module>` 
     `for item2 in output2 ['data']:` 

KeyError: 'data'

回答

0

url1 = 'http://ewodr.wodr.poznan.pl/doradztwo/swd/meteo_api.php?dane={%22token%22:%22pcss%22,%22id%22:' + str(station) + '}'

这解决了我的问题。

1

尝试用:

station= item ['id'] 
url1="http://ewodr.wodr.poznan.pl/doradztwo/swd/meteo_api.php?dane={%22token%22:%22pcss%22,%22id%22:}" +str(station) 

你试图加入一个字符串与一个整数,什么产生这个错误。

+0

谢谢@Jose但无论如何错误显示。 – SamB

+0

¿在这一行中它指定了错误?是唯一的一点,你可以有这种错误... –

+0

它适用于我完美。我使用了这里的代码,添加了str()并且它可以工作。你有一个缩进问题(至少在这里的代码复制粘贴) –