我正在将Requests和BeautifulSoup与Python 3.4配合使用,以从可能包含或不包含日语或其他特殊字符的网站上抓取信息。
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包含以下内容:“ Fate / kaleid班轮Prisma☆Ilya Zwei!” 而且我很确定这颗星是现在给我带来麻烦的原因。
正在向我抛出的错误代码:
UnicodeEncodeError: 'charmap' codec can't encode character '\u2606' in position 25: character maps to <undefined>
该页面使用utf8编码,因此我尝试使用utf8编码和解码使用r.content接收的字节字符串。我还尝试过首先使用unicode_escape进行解码,以为这是因为double \,但事实并非如此。有任何想法吗?
soup.h2.string
是Unicode字符串。控制台字符编码(例如cp437)不能表示导致错误的某些Unicode字符(☆ -U + 2606 WHITE STAR)。要解决此问题,请参阅我对“ Python,Unicode和Windows控制台”的回答。
尝试写入文件时,我仍然遇到相同的错误。
默认情况下,文件(使用创建的文件open()
)使用locale.getpreferredencoding(False)
诸如cp1252之类的文件。改用支持完整Unicode范围的显式字符编码:
import io
with io.open('title.txt', 'w', encoding='utf-8') as file:
file.write(soup.h2.string)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句