2017-04-07 64 views
1

寻求一些帮助。我正在研究一个项目,使用Python中的Beautiful Soup来抓取具体的Craigslist帖子。我可以成功显示在帖子标题中发现的emojis,但在帖子正文中未成功。我尝试了不同的变化,但迄今为止没有任何工作。任何帮助,将不胜感激。用美丽的汤编码Emojis

代码:从身体收到

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) 

错误:

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

可能与此类似:http://stackoverflow.com/questions/9644099/python-ascii-codec-cant-decode-byte – anonyXmous

回答

1

您应该使用unicode

body = unicode(body) 

请参阅美丽的汤文档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

希望得到这个帮助。

+0

感谢您的帮助和链接的参考。按预期工作。非常感激! – Phil21

+0

@ Phil21我很高兴帮忙 – Fogmoon