我在Python3.4中使用Requests和BeautifulSoup从一个可能包含也可能不包含日语或其他特殊字符的网站上获取信息。在
def startThisPage(url):
r = requests.get(str(url))
r.encoding="utf8"
print(r.content.decode('utf8'))
soup = BeautifulSoup(r.content,'html.parser')
print(soup.h2.string)
h2包含这样的内容:“命运/卡莱德班轮普里斯玛☆伊利亚·兹维!”我很确定现在给我带来麻烦的是明星。在
向我抛出的错误代码:
^{pr2}$这个页面是用utf8编码的,因此我尝试用utf8对r.content接收到的字节串进行编码和解码。我也尝试过先用unicode_escape进行解码,以为是因为double\的缘故,但事实并非如此。有什么想法吗?在
soup.h2.string
是Unicode字符串。控制台字符编码(如cp437)不能表示导致错误的一些Unicode字符(☆U+2606 WHITE STAR)。要解决此问题,请参见my answer to "Python, Unicode, and the Windows console" question。在默认情况下,文件(使用
open()
创建)使用locale.getpreferredencoding(False)
,如cp1252。请改用支持完整Unicode范围的显式字符编码:相关问题 更多 >
编程相关推荐