2013-05-02 76 views
1

當我在python shell中逐一輸入命令時,用於從url下載json文件的代碼運行正常。但是,當我嘗試運行包含此代碼的模塊時,我得到:ValueError: No JSON object could be decoded。任何想法是爲什麼?我運行python 2.7。代碼在shell中運行,但不是從模塊中運行

import urllib2 
from urllib2 import Request 
import json 
import re 

url1 = "http://www.skyscanner.net/flights/lond/nyca/130514/130525/airfares-from-london-to-new-york-in-may-2013.html" 

req = Request(url1) 
res = urllib2.urlopen(req) 
the_page = res.read() 
theText = str(the_page) 

myre = re.compile(r'"SessionKey":"((([a-z0-9]+-)+)[a-z0-9]{12})"') 
match = re.search(myre, theText) 

print match.group(1) 

url2 = "http://www.skyscanner.net/dataservices/routedate/v2.0/"+str(match.group(1)) 
htmltext = urllib2.urlopen(url2) 
data = json.load(htmltext) 

現在整個代碼:

import urllib2 
from urllib2 import Request, urlopen, URLError, HTTPError 
import json 
import re 


url1 = "http://www.skyscanner.net/flights/lond/nyca/130514/130525/airfares-from-london-to-new-york-in-may-2013.html" 

req = Request(url1) 
res = urllib2.urlopen(req) 
the_page = res.read() 
theText = str(the_page) 

myre = re.compile(r'"SessionKey":"((([a-z0-9]+-)+)[a-z0-9]{12})"') 
match = re.search(myre, theText) 

url2 = "http://www.skyscanner.net/dataservices/routedate/v2.0/%s" % str(match.group(1)) 

req2 = urllib2.Request(url2) 

try: 
    response = urlopen(req2) 
except HTTPError as e: 
    print 'The server couldn\'t fulfill the request.' 
    print 'Error code: ', e.code 
except URLError as e: 
    print 'We failed to reach a server.' 
    print 'Reason: ', e.reason 
else: 
    data = json.loads(response.read()) 

print data["SessionKey"] 
+0

這是因爲你的JSON對象無法解碼,即'htmltext'不是json。 – danodonovan 2013-05-02 11:43:38

+0

但爲什麼它會在shell中工作呢? – maddy 2013-05-02 11:46:03

+0

它不工作在我的shell中,對不起 – danodonovan 2013-05-02 11:48:40

回答

0

哈!你是對的,這是shell使用和腳本使用的區別。無論url1正在做什麼,在您打開url2時尚未完成(遠程)。等一會兒就可以完成所有工作!

import time 

url2 = "http://www.skyscanner.net/dataservices/routedate/v2.0/%s" % str(match.group(1)) 

time.sleep(5) 

req2 = urllib2.Request(url2) 

所以它不是你的代碼......哼!

+0

男人!幹得好!謝謝! – maddy 2013-05-02 14:11:01

相關問題