BeautifulSoup and LXML are popular Python libraries for web scraping and for parsing HTML or XML documents. BeautifulSoup is known for its simplicity and ease of use while LXML is renowned for its speed and its support of XPath expressions. Both libraries are compatible, LXML can even use BeautifulSoup as a parser. Still, it can be unclear how to use them both at the same time.

In some cases it can be useful to convert a BeautifulSoup object into an LXML tree, for example to pass it on to a library expecting LXML input. The working example below uses the date extraction library I am working on, htmldate.

Installation

$ pip install beautifulsoup4 lxml
$ pip install htmldate  # for the example

Three steps

  1. Parse an HTML document with BeautifulSoup
  2. Use LXML’s convert_tree function to convert the BeautifulSoup object into a list of LXML elements
  3. Put these elements back under a common html root

The last step is necessary because convert_tree returns the children of the html element, usually head and body, and not a single tree. It turned out that taking only the first element of the list keeps the head and loses the rest of the page.

Here is a working example:

# required libraries
from bs4 import BeautifulSoup
from lxml import html
from lxml.html.soupparser import convert_tree

# working example with htmldate
from htmldate import find_date

# document as string
doc = '<html><head><title>Test</title></head><body><time datetime="2024-02-02">Feb 2, 2024</time></body></html>'

# 1. Parse
soup = BeautifulSoup(doc, "lxml")
# 2. Convert
elements = convert_tree(soup)
# 3. Reassemble
lxml_tree = html.Element("html")
lxml_tree.extend(elements)

# use the result
find_date(lxml_tree)  # '2024-02-02'
lxml_tree.xpath("//title/text()")  # ['Test']

Summing up

Converting a BeautifulSoup object into an LXML tree only takes a few lines. It allows for combining the strengths of both libraries, for instance the robust parsing of BeautifulSoup and the XPath expressions of LXML.

Links