Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Beautiful Soup and Table Scraping - lxml vs html parser

I'm trying to extract the HTML code of a table from a webpage using BeautifulSoup.

<table class="facts_label" id="facts_table">...</table>

I would like to know why the code bellow works with the "html.parser" and prints back none if I change "html.parser" for "lxml".

#! /usr/bin/python

from bs4 import BeautifulSoup
from urllib import urlopen

webpage = urlopen('http://www.thewebpage.com')
soup=BeautifulSoup(webpage, "html.parser")
table = soup.find('table', {'class' : 'facts_label'})
print table
like image 817
LaGuille Avatar asked Sep 07 '14 20:09

LaGuille


People also ask

What is the difference between HTML parser and lxml?

lxml is also a similar parser but driven by XML features than HTML. It has dependency on external C libraries. It is faster as compared to html5lib. Lets observe the difference in behavior of these two parsers by taking a sample tag example and see the output.

Is lxml faster than BeautifulSoup?

lxml is way faster than BeautifulSoup - this may not matter if all you're waiting for is the network. But if you're parsing something on disk, this may be significant.

What is lxml in BeautifulSoup?

lxml can make use of BeautifulSoup as a parser backend, just like BeautifulSoup can employ lxml as a parser. When using BeautifulSoup from lxml, however, the default is to use Python's integrated HTML parser in the html. parser module.

What is faster than BeautifulSoup?

Speed. Scrapy is incredibly fast. Its ability to send asynchronous requests makes it hands-down faster than BeautifulSoup. This means that you'll be able to scrape and extract data from many pages at once.


1 Answers

There is a special paragraph in BeautifulSoup documentation called Differences between parsers, it states that:

Beautiful Soup presents the same interface to a number of different parsers, but each parser is different. Different parsers will create different parse trees from the same document. The biggest differences are between the HTML parsers and the XML parsers.

The differences become clear on non well-formed HTML documents.

The moral is just that you should use the parser that works in your particular case.

Also note that you should always explicitly specify which parser are you using. This would help you to avoid surprises when running the code on different machines or virtual environments.

like image 194
alecxe Avatar answered Sep 19 '22 00:09

alecxe