How to use: Input in terminal
Copy CodeThe code is as follows:
Python weather.py http://www.weather.com.cn/weather/101010100.shtml
BEIJING 6-Day weather data JSON format
Copy the Code code as follows:
#coding =utf-8
#weather. py
Import Urllib
Import re
Import Simplejson
Import Sys
If Len (sys.argv)! = 2:
print ' please enter:python ' + sys.argv[0] + ' '
Exit (0)
url = sys.argv[1];
def readurlpagecontent (URL): #获取页面的所有数据 progressive Read
Webpage = urllib.urlopen (URL);
line = Webpage.readline ();
data = '
While line:
data = data + Line.strip (); #去除每行两边的的空格
line = Webpage.readline ();
Return data
def getdatabody (data):
Reg = Re.compile (R ' (?:(?!) ');
Matchs = Reg.findall (data,re. I);
If Len (matchs) > 0:
return Matchs[0]
Return None
def getsixdayweather (data):
Regs = Re.compile (R ' > (?:(?! <) (?! >) (?! var).) +) < ');
Datas = Regs.findall (data)
If Len (datas) > 12:
Datas = Datas[12:len (datas)-7]; #提取其中的78项 that is, the weather data for the next 6 days has 13 related information per day
return datas
Return None
data = readurlpagecontent (URL);
Match_data = getdatabody (data)
if Match_data = = None:
print ' Get Weather data fail '
Exit (0)
Weathers_data = Getsixdayweather (match_data)
if Weathers_data = = None:
print ' Get Six day info fail '
Exit (0)
Count = Len (weathers_data);
Groups_item_count = COUNT/6;
Weathers = {};
groups = [];
Start = 0
For item in Weathers_data:
If (start% groups_item_count) = = 0:
groups = [];
weathers[(' Day ' +str (Start/groups_item_count + 1)] = groups;
Groups.append (item)
Start = start + 1
Print Simplejson.dumps (weathers, encoding= ' UTF-8 ', ensure_ascii=false)
Note: The third-party JSON library Simplejson is used in this article, and the installation method is referenced below:
1. Download: http://pypi.python.org/pypi/simplejson/, file for compressed file
2. Unzip: You can right-click: Unzip the file. For example: D:/simplejson
3. Start---Run---input command: cmd
4. Go to the catalogue (e.g.: D:/simplejson)
Copy the Code code as follows:
CD D:/simplejson
5. Run the installation file: setup.py install