beautifulsoup4-4.3.0
很好的一个网络爬虫工具 class MutilHTMLParser(HTMLParser): def __init__(self, env, tags, select_name): self.env = env self.log = env.log self.taglevels=[] self.handledtags=tags #['select'] #['body'] #['title','body'] #提出标签 self.processing=None sel f.select_name=select_name self.a_map={} self.a_map['ui'] = '' self.a_map['db'] = '' self.map_table=[] HTMLParser.__init__(self) def handle_starttag(self,tag,attrs): if tag in self.handledtags: self.data='' self.values=[] if tag =='select': for name,value in attrs: if name=='name': if value==self.select_name: self.processing=tag #self.log.error('=== in value=%s ', value) else: self.processing=None #self.log.error('=== out value=%s ', value) if self.processing: if tag =='option': for name,value in attrs: if name=='value': #self.log.error('1 value=%s', value) self.a_map['db'] = value #self.log.error('1 a_map=%s', self.a_map) def handle_data(self,data): if self.processing: #self.log.error('2 data=%s', self.data) self.data +=data data = data.replace('\n ','') data = data.replace(' ','') if data != '' and self.a_map['db'] != '': self.a_map['ui'] = data a_map={} a_map['ui']=self.a_map['ui'] a_map['db']=self.a_map['db'] self.map_table.append(a_map) #self.log.error('2 a_map=%s', self.a_map) #self.log.error('2 map_table=%s', self.map_table) self.a_map['ui'] = '' self.a_map['db'] = '' #else: # self.log.error('2 data=%s', data) def handle_endtag(self,tag): if tag==self.processing: #self.log.error('3 %s', str(tag)+':'+str(self.getdata())) #self.log.error('3 map_table=%s', self.map_table) self.processing=None def getdata(self): return self.map_table f.select_name=select_name self.a_map={} self.a_map['ui'] = '' self.a_map['db'] = '' self.map_table=[] HTMLParser.__init__(self) def handle_starttag(self,tag,attrs): if tag in self.handledtags: self.data='' self.values=[] if tag =='select': for name,value in attrs: if name=='name': if value==self.select_name: self.processing=tag #self.log.error('=== in value=%s ', value) else: self.processing=None #self.log.error('=== out value=%s ', value) if self.processing: if tag =='option': for name,value in attrs: if name=='value': #self.log.error('1 value=%s', value) self.a_map['db'] = value #self.log.error('1 a_map=%s', self.a_map) def handle_data(self,data): if self.processing: #self.log.error('2 data=%s', self.data) self.data +=data data = data.replace('\n ','') data = data.replace(' ','') if data != '' and self.a_map['db'] != '': self.a_map['ui'] = data a_map={} a_map['ui']=self.a_map['ui'] a_map['db']=self.a_map['db'] self.map_table.append(a_map) #self.log.error('2 a_map=%s', self.a_map) #self.log.error('2 map_table=%s', self.map_table) self.a_map['ui'] = '' self.a_map['db'] = '' #else: # self.log.error('2 data=%s', data) def handle_endtag(self,tag): if tag==self.processing: #self.log.error('3 %s', str(tag)+':'+str(self.getdata())) #self.log.error('3 map_table=%s', self.map_table) self.processing=None def getdata(self): return self.map_table
用户评论