coding utf-8 To change this template choose Tools Templates and open t

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#coding: utf-8
# To change this template, choose Tools | Templates
# and open the template in the editor.
import urllib, sys
import re
import tempfile
from BeautifulSoup import BeautifulSoup
class Downloader():
city_id = None
def __init__(self, city):
if not(isinstance(city, str) or isinstance(city, unicode)):
raise ValueError, 'Неправильный тип переменной'
cities = urllib.urlopen("http://weather.yandex.ru/russia")
soup = BeautifulSoup(cities.read())
cities = soup.findAll('a')
for c in cities:
if c.string == city:
self.city_id = re.search('<a href="(.+)".+', str(c)).groups()[0].replace('/', '')
def to_temp_file(self):
if not self.city_id:
print 'Извините, такого города нет в базе'
sys.exit(1)
file = tempfile.NamedTemporaryFile(delete=False)
file.write(urllib.urlopen('http://weather.yandex.ru/%s/' % self.city_id).read())
return file.name
class WeatherFinder():
temp_file = None
def __init__(self, temp_file):
self.temp_file = temp_file
def weather(self):
text = open(self.temp_file, 'r').read().replace('\n', '')
text = re.sub('<script.*?script>', '', text)
soup = BeautifulSoup(text)
table = soup.find('table', { "class": "b-forecast-brief "})
data = []
for el in re.findall('<span>(.*?)</span>', str(table.tr))[:5]:
data.append([el, None, None])
i = 0
for el in re.findall('<td.*?>(.*?)</td>', str(table.contents[3]))[:5]:
data[i][1] = re.sub('<.*>', '', el)
i += 1
i = 0
for el in re.findall('<td.*?>(.*?)</td>', str(table.contents[5]))[:5]:
data[i][2] = re.sub('<.*?>', '', el)
i += 1
return reduce(lambda x,y: x+'\n'+', '.join(y), data, '')[1:]
if __name__ == "__main__":
downloader = Downloader(u'Набережные Челны')
temp_file = downloader.to_temp_file()
finder = WeatherFinder(temp_file)
print finder.weather()