How to: Enter in terminal
Copy Code code as follows:
Python weather.py http://www.weather.com.cn/weather/101010100.shtml
Weather data in Beijing 6 days JSON format
Copy 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] + ' <url> '
Exit (0)
url = sys.argv[1];
def readurlpagecontent (URL): #获取页面的所有数据 read-by-line
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 ' (<div class=\ "weatheryubaobox\" >) (?:(?! <DIV) (?! </DIV).) *</div>) ');
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 the weather data for the following 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 as compressed file
2. Decompression: Can directly right key: Extract files. For example: D:/simplejson
3. Start---Run---input command: cmd
4. Access to directory (e.g. D:/simplejson)
Copy Code code as follows:
5. Run the installation file: setup.py install