Home » Html » Python: Is there a built in package to parse html into dom

Python: Is there a built in package to parse html into dom

Posted by: admin November 29, 2017 Leave a comment

Questions:

I found HTMLParser for sax and xml.minidom for xml. I have a pretty well formed html so I don’t need a too strong parser – any suggestions?

Answers:

Take a look at BeautifulSoup. It’s popular and excellent at parsing HTML.

Questions:
Answers:

I would recommend lxml. I like BeautifulSoup, but there are maintenance issues generally and compatibility issues with the later releases. I’ve been happy using lxml.


Later: the best recommendations are to use lxml, html5lib, or BeautifulSoup 3.0.8. BeautifulSoup 3.1.x is meant for python 3.x and is known to have problems with earlier python versions, as noted on the BeautifulSoup website.

Ian Bicking has a good article on using lxml.

ElementTree is a further recommendation, but I have never used it.


2012-01-18: someone has come by and decided to downvote me and Bartosz because we recommended python packages that are easily obtained but not part of the python distribution. So for the highly literal StackOverflowers: “You can use xml.dom.minidom, but no one will recommend this over the alternatives.”

Questions:
Answers:

BeautifulSoup and lxml are great, but not appropriate answers here since the question is about builtins. Here is an example of using the builtin minidom module to parse an HTML string. Tested with cPython 3.5.2:

from xml.dom.minidom import parseString

html_string = """
<!DOCTYPE html>
<html><head><title>title</title></head><body><p>test</p></body></html>
"""

# extract the text value of the document's <p> tag:
doc = parseString(html_string)
paragraph = doc.getElementsByTagName("p")[0]
content = paragraph.firstChild.data

print(content)

Questions:
Answers:

To handle DOM objects, you can use HTMLDOM for python.

Leave a Reply

Your email address will not be published. Required fields are marked *