2013-12-16 91 views
0

這是我的代碼來訪問一個網頁,但我需要添加參數: 1.通過從文件 讀取一行添加第一個參數2.第二個參數是一個計數器,以連續訪問頁面在python中添加url參數

import urllib2 
import json,os 

f = open('codes','r') 
for line in f.readlines(): 
    id = line.strip('\n') 
    url = 'http://api.opencorporates.com/v0.2/companies/search?q=&jurisdiction_code=%s&per_page=26&current_status=Active&page=%d' 
    i = 0 
    directory = id 
    os.makedirs(directory) 
    while True: 
     i += 5 
     req = urllib2.Request('%s%s%d' % (url,id, i)) 
     print req 
     try: 
      response = urllib2.urlopen('%s%s%d' % (url, id, i)) 
     except urllib2.HTTPError, e: 
      break 
     content = response.read() 
     fo = str(i) + '.json'  
     OUTFILE = os.path.join(directory, fo) 
     with open(OUTFILE, 'w') as f: 
      f.write(content) 

這不斷創建空目錄。我知道URL參數有問題。如何糾正這一點?

+0

我認爲你的問題是在你的'Request'調用中。在我頭頂,字符串格式看起來不對。把你要求的網址放入一個變量中並打印出來,看看它的樣子。 – willy

+0

這就是它正在打印的內容:http://api.opencorporates.com/v0.2/companies/search?q=&jurisdiction_code=%s&per_page=26¤t_status=Active&page=%dae_az5 在最後附加參數。 – blackmamba

+0

然後,我會添加一個答案,我確切地看到問題是什麼。 – willy

回答

0

您需要更改這些位:

'%s%s%d' % (url,id, i) 

要這樣:

url % (id, i) 

你現在正在做的是創建一個字符串像'<url><id><i>'而不是字符串的替代。

+0

它的工作原理。非常感謝。 – blackmamba

2

看起來你想要做的是插入idiurl,但字符串格式化你使用此串接urlidi。嘗試修改此:

req = urllib2.Request('%s%s%d' % (url,id, i)) 

進入這個:

req = urllib2.Request(url % (id, i)) 

這是否給你你想要的結果?

此外,您使用的字符串格式化語法已棄用;目前首選的語法詳見PEP 3101 -- Advanced String Formatting。所以,更好的是做:

url = 'http://api.opencorporates.com/v0.2/companies/search?q=&jurisdiction_code={0}&per_page=26&current_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 "<pyshell#18>", line 1, in <module> 
    '{} 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詳細,如果你有興趣。

+0

非常感謝。我將用新格式替換它。 – blackmamba