2013-11-22 213 views
1

我是初學者到python。我是Easy APIs Project(http://gcdc2013-easyapisproject.appspot.com)的開發人員,正在使用我的項目對天氣API進行Python實現。訪問http://gcdc2013-easyapisproject.appspot.com/APIs_Doc.html查看天氣API。以下是我的實現,但它返回HTTPError: HTTP Error 400: Bad request錯誤。HTTPError:HTTP錯誤400:錯誤的請求urllib2

import urllib2 

def celsius(a): 
    responsex = urllib2.urlopen('http://gcdc2013-easyapisproject.appspot.com/unitconversion?q='+a+' in celsius') 
    htmlx = responsex.read() 
    responsex.close() 
    htmlx = html[1:] #remove first { 
    htmlx = html[:-1] #remove last } 
    htmlx = html.split('}{') #split and put each resutls to array 
    return str(htmlx[1]); 

print "Enter a city name:", 
q = raw_input() #get word from user 
response = urllib2.urlopen('http://gcdc2013-easyapisproject.appspot.com/weather?q='+q) 
html = response.read() 
response.close() 
html = html[1:] #remove first { 
html = html[:-1] #remove last } 
html = html.split('}{') #split and put each resutls to array 
print "Today weather is " + html[1] 
print "Temperature is " + html[3] 
print "Temperature is " + celsius(html[3]) 

請幫助我..

回答

0

查詢字符串應該使用urllib.quoteurllib.quote_plus被引用:

import urllib 
import urllib2 

def celsius(a): 
    responsex = urllib2.urlopen('http://gcdc2013-easyapisproject.appspot.com/unitconversion?q=' + urllib.quote(a + ' in celsius')) 
    html = responsex.read() 
    responsex.close() 
    html = html[1:] #remove first { 
    html = html[:-1] #remove last } 
    html = html.split('}{') #split and put each resutls to array 
    return html[0] 

print "Enter a city name:", 
q = raw_input() #get word from user 
response = urllib2.urlopen('http://gcdc2013-easyapisproject.appspot.com/weather?q='+urllib.quote(q)) 
html = response.read() 
print repr(html) 
response.close() 
html = html[1:] #remove first { 
html = html[:-1] #remove last } 
html = html.split('}{') #split and put each resutls to array 
print "Today weather is " + html[1] 
print "Temperature is " + html[3] 
print "Temperature is " + celsius(html[3].split()[0]) 

除此之外,我修改celsius使用html而不是htmlx。原碼混合使用htmlhtmlx

+0

爲什麼不使用urllib2.quote? – selllikesybok

+0

@selllikesybok,'urllib2.quote'是對'urllib.quote'的引用。試試'import urllib,urllib2;斷言urllib2.quote是urllib.quote'。 – falsetru

+0

答案是正確的。 –

0

我找到了答案。查詢應引用urllib2.quote(q)

+0

事實上,q?之後的整個部分都需要引用。 – selllikesybok

+0

@selllikesybok是 –

+1

[接受你自己的答案不會給你聲望。](https://blog.stackoverflow.com/2009/01/accept-your-own-answers/)你能再次接受我的答案嗎? :) – falsetru