<s> import logging <EOL> from xml . dom import minidom , Node <EOL> from xml . parsers . expat import ExpatError , ErrorString <EOL> class GoodReadsParser ( object ) : <EOL> def parse_result ( self , url_handler ) : <EOL> try : <EOL> goodreads_dom = minidom . parse ( url_handler ) <EOL> return goodreads_dom <EOL> except ExpatError , e : <EOL> logging . error ( "<STR_LIT>" % ( <EOL> ErrorString ( e . code ) , e . lineno , e . offset ) ) <EOL> return None <EOL> def get_text ( self , element ) : <EOL> value = "<STR_LIT>" <EOL> for text in element . childNodes : <EOL> try : <EOL> value += text . data <EOL> except AttributeError : <EOL> logging . error ( "<STR_LIT>" + text . toxml ( ) ) <EOL> raise <EOL> if value : <EOL> return value . strip ( ) <EOL> else : <EOL> return None <EOL> def parse_books ( self , url_handler ) : <EOL> goodreads_dom = self . parse_result ( url_handler ) <EOL> books = [ ] <EOL> for book_element in goodreads_dom . getElementsByTagName ( "<STR_LIT>" ) : <EOL> book = self . handle_book ( book_element ) <EOL> if book : <EOL> books . append ( book ) <EOL> return books <EOL> def handle_book ( self , book_element ) : <EOL> book = { } <EOL> for child_node in book_element . childNodes : <EOL> value = "<STR_LIT>" <EOL> if child_node . nodeType == Node . TEXT_NODE : <EOL> continue <EOL> elif child_node . nodeName == "<STR_LIT>" : <EOL> value = self . handle_authors ( child_node ) <EOL> elif child_node . nodeName == "<STR_LIT>" : <EOL> logging . info ( "<STR_LIT>" ) <EOL> continue <EOL> else : <EOL> value = self . get_text ( child_node ) <EOL> book [ child_node . nodeName ] = value <EOL> return book <EOL> def parse_shelfs ( self , url_handler ) : <EOL> goodreads_dom = self . parse_result ( url_handler ) <EOL> shelfs = [ ] <EOL> for shelf_element in goodreads_dom . getElementsByTagName ( "<STR_LIT>" ) : <EOL> shelf = self . handle_shelf ( shelf_element ) <EOL> if shelf : <EOL> shelfs . append ( shelf ) <EOL> return shelfs <EOL> def handle_shelf ( self , shelf_element ) : <EOL> shelf = { } <EOL> for child_node in shelf_element . childNodes : <EOL> value = "<STR_LIT>" <EOL> if child_node . nodeType == Node . TEXT_NODE : <EOL> continue <EOL> else : <EOL> value = self . get_text ( child_node ) <EOL> shelf [ child_node . nodeName ] = value <EOL> return shelf <EOL> def handle_authors ( self , authors_element ) : <EOL> authors = [ ] <EOL> for child_node in authors_element . childNodes : <EOL> author = self . handle_author ( child_node ) <EOL> if author : <EOL> authors . append ( author ) <EOL> return authors <EOL> def handle_author ( self , author_element ) : <EOL> author = { } <EOL> for child_node in author_element . childNodes : <EOL> value = "<STR_LIT>" <EOL> if child_node . nodeType == Node . TEXT_NODE : <EOL> continue <EOL> else : <EOL> value = self . get_text ( child_node ) <EOL> author [ child_node . nodeName ] = value <EOL> if author : <EOL> return author <EOL> else : <EOL> return None </s>
