Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse malformed HTML in python

Tags:

python

html

lxml

I need to browse the DOM tree of a parsed HTML document.

I'm using uTidyLib before parsing the string with lxml

a = tidy.parseString(html_code, options) dom = etree.fromstring(str(a))

sometimes I get an error, it seems that tidylib is not able to repair malformed html.

how can I parse every HTML file without getting an error (parsing only some parts of files that can not be repaired)?

like image 319
lorenzov Avatar asked May 24 '09 20:05

lorenzov


2 Answers

Beautiful Soup does a good job with invalid/broken HTML

>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup("<htm@)($*><body><table <tr><td>hi</tr></td></body><html")
>>> print soup.prettify()
<htm>
 <body>
  <table>
   <tr>
    <td>
     hi
    </td>
   </tr>
  </table>
 </body>
</htm>
like image 129
dbr Avatar answered Oct 17 '22 14:10

dbr


Since you are already using lxml, have you tried lxml's ElementSoup module?

If ElementSoup can't repair the HTML then you'll probably need to apply your own filters first that are based on your own observations of how the data is broken.

like image 27
Van Gale Avatar answered Oct 17 '22 14:10

Van Gale