问题
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> hello </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> hello </td>
回答1:
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")
来源:https://stackoverflow.com/questions/16135951/scrape-using-beautiful-soup-preserving-nbsp-entities