Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scrape using Beautiful Soup preserving   entities

I would like to scrape a table from the web and keep the   entities intact so that I can republish as HTML later. BeautifulSoup seems to be converting these to spaces though. Example:

from bs4 import BeautifulSoup

html = "<html><body><table><tr>"
html += "<td>&nbsp;hello&nbsp;</td>"
html += "</tr></table></body></html>"

soup = BeautifulSoup(html)
table = soup.find_all('table')[0]
row = table.find_all('tr')[0]
cell = row.find_all('td')[0]

print cell

observed result:

<td> hello </td>

required result:

<td>&nbsp;hello&nbsp;</td>
like image 548
Holy Mackerel Avatar asked Apr 21 '13 20:04

Holy Mackerel


1 Answers

In bs4 convertEntities parameter to BeautifulSoup constructor is not supported anymore. HTML entities are always converted into the corresponding Unicode characters (see docs).

According to docs, you need to use an output formatter, like this:

print soup.find_all('td')[0].prettify(formatter="html")
like image 61
alecxe Avatar answered Nov 25 '22 10:11

alecxe