-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpgefetch
More file actions
144 lines (128 loc) · 4.41 KB
/
Copy pathpgefetch
File metadata and controls
144 lines (128 loc) · 4.41 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#!/usr/bin/env python
import socket; del socket.ssl # force use of cURL, because it's faster
import sys, time, keyword
flush = sys.stdout.flush
from scrape import *
s.verbose = 1
def getid(element):
text = element.text.replace('_', ' ').replace('-', ' ')
text = re.sub(r'[^\w\s]', '', element.text)
return '_'.join(text.lower().split())
def trystr(text):
try:
return str(text)
except:
return text
def nospans(tr):
return int(tr.first('td').get('colspan', 1)) == 1
def getrecord(headings, tr):
record = {}
for heading, td in zip(headings, tr.all('td')):
try:
heading = str(heading)
except:
pass
try:
value = td.number
except:
value = td.text.strip()
try:
value = str(value)
except:
pass
if keyword.iskeyword(heading):
heading += '_'
record[heading] = value
return record
def getservices():
d = s.go('http://www.pge.com/myhome')
b = d.all('form')[1].buttons[0]
s.submit(b, USER='kingman', PASSWORD='carb0n', redirects=0)
s.go('/csol/actions/login.do?aw')
s.follow('Business Tools')
d = s.follow(iregex(r'view\s+all\s+\d+\s+services'))
services = {}
while 1:
h = d.find(iregex(r'Service\s+ID\s+Number'))
rows = filter(nospans, h.enclosing('table').all('tr'))
headings = map(getid, rows.pop(0).all('td'))
for row in rows:
if row.all('a', href=ANY):
record = getrecord(headings, row)
record['url'] = s.resolve(row.first('a')['href'])
services[record['service_id_number']] = record
try:
d = s.follow(regex(r'NEXT \d+'))
except ScrapeError:
break
return services
def shortrepr(x):
if type(x) in [int, long, float]:
return str(x)
return repr(x)
def dump(d):
"""Produce a more compact representation of a dictionary, loadable
with eval() just by enclosing the text between "dict(" and ")"."""
return ', '.join(('%s=%s') % (key, shortrepr(d[key]))
for key in sorted(d.keys()))
call_re = r'(\w+)\s*\('
def_re = r'function\s+__0__\(.*?{(.*?)}'
var_re = r'__0__\s*=\s*[\'"](.*?)[\'"]'
cookielit_re = r'\bdocument.cookie\s*=\s*[\'"](.*?)[\'"]'
cookievar_re = r'\bdocument.cookie\s*=\s*(\w+)'
def getservice(url):
d = s.go(url)
# It's awful: the billing history link doesn't specify the service ID
# in the URL. It calls a JavaScript function to put the service ID in
# a cookie, which the linked page depends on to get the history data.
link = d.first('a', content=regex('.*History'))
onclick = link.get('onclick', '')
if onclick.strip().startswith('javascript:'):
match = re.search(call_re, onclick)
if match:
func = match.group(1)
funcdef = s.doc.find(regex(def_re, func)).content
match = re.search(cookielit_re, funcdef)
if not match:
match = re.search(cookievar_re, funcdef)
if match:
var = match.group(1)
match = regex(var_re, var).search(funcdef)
if match:
s.setcookie(match.group(1))
d = s.go(link['href'])
# Customer profile table.
profile = {}
try:
table = d.find(iregex(r'customer\s+profile')).enclosing('table')
key = ''
for td in table.all('td', colspan=MISSING):
if td['class'] == 'dataTable':
key = getid(td)
if td['class'] == 'dataTableData' and key:
profile[trystr(key)] = trystr(td.text.strip())
except ScrapeError:
pass
# Billing history table.
records = []
try:
table = d.last('table', content=iregex(r'billing\s+history'))
rows = filter(nospans, table.all('tr'))
headings = map(getid, rows.pop(0).all('td'))
for row in rows:
records.append(getrecord(headings, row))
except ScrapeError:
pass
return profile, records
services = getservices()
for service, record in services.items():
print '\n# Service %s (downloaded %04d-%02d-%02dT%02d:%02d:%02dZ)' % (
(service,) + time.gmtime()[:6])
print dump(record)
flush()
profile, records = getservice(record['url'])
print dump(profile)
flush()
for record in records:
print dump(record)
flush()