1

Dears,

I need to collect the Data in the below HTML in a array of string

parser.feed( <table><tr><td><a href="https://rads.stackoverflow.com/amzn/click/com/B00JX1ZS5O" rel="nofollow noreferrer" target="_blank"><img src="https://images-na.ssl-images-amazon.com/images/I/41B39oDSGQL._SL160_.jpg" alt="Product Image" style='border:0'/></a></td><td><tr><td>List Price: <strike>$34.99</strike></td></tr><tr><td><b>Deal Price: $7.99</b></td></tr><tr><td>You Save: $2.00 (20%)</td></tr><tr><td>Sabrent 4-Port USB 3.0 Hub with Individual Power Switches and LEDs (HB-UM43)</td></tr><tr><td>Expires Jun 15, 2017</td></tr></td></tr></table>)

so I used the below but

class MyHTMLParser(HTMLParser):

    def handle_data(self, data):
        self.Datacollected(data)
        return (data)
parser = MyHTMLParser() 
Collector=[]
Collector.append[parser.feed("HTML Code HERE")]

but it is Always Empty

1 Answer 1

1

The feed method is parsing one HTML element at a time, and handing it over to the handle_data method. The return value of feed is None, that's why your list is empty. If you want to keep all the data fed into the parser, you need to add some data structure in the __init__() method, like a list, include the data into it within the handle_data method, and implement another method that returns your data, e.g.:

class MyHTMLParser(HTMLParser):

    def __init__(self, **kwargs, *args):
        self.d = []
        super().__init__()

    def handle_data(self, data):
        self.d.append(data)
        return (data)

    def return_data(self):
        return self.d

collector=[] 
parser = MyHTMLParser() 
parser.feed("HTML Code HERE")
collector.append(parser.return_data())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.