-
Notifications
You must be signed in to change notification settings - Fork 0
/
exer12.py
38 lines (31 loc) · 1.07 KB
/
exer12.py
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
import requests
import xml.etreeElementTree as ET
from xml.parser.expat import ParserCreate
class DefaultSaxHandler(object):
def __init__(self,provinces):
self.provinces = provinces
def start_element(self,name,attrs):
if name != 'map':
name = attrs['title']
number = attrs['href']
self.provinces.append((name,number))
def end_element(self,name):
pass
def char_data(self,text):
pass
def get_provinces(url):
content = requests.get(url).content.decode('gb2312')
start = content.find('<map name=\"map_86" id=\"map_86\">')
end = content.find('</map>')
content = content[start:end + len('</map>')].strip()
print(content)
provinces = []
handler = DefaultSaxHandler(provinces)
parser = ParserCreate()
parser.StartElementHandler = handler.start_element
parser.EndElementHandler = handler.end_element
parser.CharacterDataHandler = handler.char_data
parser.Parse(content)
return provinces
provinces = get_provinces('http://www.ip138.com/post')
print(provinces)