用美丽的汤编码表情符号

Encoding Emojis with Beautiful Soup

寻求帮助。我正在开展一个项目,使用 Python 中的 Beautiful Soup 抓取特定的 Craigslist posts。我可以成功显示在 post 标题中找到的表情符号,但在 post body 中不成功。我尝试了不同的变体,但到目前为止没有任何效果。任何帮助将不胜感激。

代码:

f = open("clcondensed.txt", "w")
html2 = requests.get("https://raleigh.craigslist.org/wan/6078682335.html")
soup = BeautifulSoup(html2.content,"html.parser")
#Post Title 
title = soup.find(id="titletextonly")       
title1 = soup.title.string.encode("ascii","xmlcharrefreplace")
f.write(title1)
#Post Body  
body = soup.find(id="postingbody")          
body = str(body)
body = body.encode("ascii","xmlcharrefreplace")
f.write(body)

从 body 收到错误:

'ascii' codec can't decode byte 0xef in position 273: ordinal not in range(128)

你应该使用unicode

body = unicode(body)

请参考 Beautiful Soup 文档 NavigableString


更新:

抱歉回答这么快。这是不对的。

这里你应该使用 lxml 解析器而不是 html 解析器,因为 html 解析器不能很好地支持 NCR (Numeric Character Reference) 表情符号。

在我的测试中,当 NCR 表情符号十进制值大于 65535 时,例如您的 html 演示表情符号 🚢HTML 解析器只是使用错误的 unicode 对其进行解码\ufffdu"\U0001F6A2"。我找不到准确的 Beautiful Soup reference,但是 lxml 解析器就可以了。

下面是测试代码:

import requests
from bs4 import BeautifulSoup
f = open("clcondensed.txt", "w")
html = requests.get("https://raleigh.craigslist.org/wan/6078682335.html")
soup = BeautifulSoup(html.content, "lxml")
#Post Title
title = soup.find(id="titletextonly")
title = unicode(title)
f.write(title.encode('utf-8'))
#Post Body
body = soup.find(id="postingbody")
body = unicode(body)
f.write(body.encode('utf-8'))
f.close()

你可以参考 lxml entity handling 做更多的事情。

如果不安装lxml,只需参考lxml installing

希望对您有所帮助。