看起来您要做的是将id和{}插入url,但是这里使用的字符串格式连接url、id和{}。尝试改变这个:req = urllib2.Request('%s%s%d' % (url,id, i))
在这方面:
^{pr2}$
这能给你想要的结果吗?在
另外,您使用的字符串格式语法已被弃用;当前首选的语法在PEP 3101 Advanced String Formatting中有详细说明。所以最好是:url = 'http://api.opencorporates.com/v0.2/companies/search?q=&jurisdiction_code={0}&per_page=26¤t_status=Active&page={1}'
...
req = urllib2.Request(url.format(id, i))
不是%s和%d,而是使用大括号({})作为参数的占位符。在大括号内,可以放置元组索引:>>> 'I like to {0}, {0}, {0}, {1} and {2}'.format('eat', 'apples', 'bananas')
'I like to eat, eat, eat, apples and bananas'
如果只使用大括号,则每个占位符使用一个参数,并且忽略其他参数;例如:>>> '{} and {} and {}'.format(1, 2, 3)
'1 and 2 and 3'
>>> '{} and {} and {}'.format(1, 2, 3, 4)
'1 and 2 and 3'
>>> '{} and {} and {}'.format(1, 2)
Traceback (most recent call last):
File "", line 1, in
'{} and {} and {}'.format(1, 2)
IndexError: tuple index out of range
还可以使用关键字参数,因此可以使用字典解包:>>> d = {'adj':'funky', 'noun':'cheese', 'pronoun':'him'}
>>> 'The {adj} {noun} intrigued {pronoun}.'.format(**d)
'The funky cheese intrigued him.'
如果您感兴趣的话,还有更多的特性,请参见PEP。在