Scrape using Beautiful Soup preserving   entities

人盡茶涼 提交于 2019-12-23 07:48:53

问题


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>

回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!