首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在python中将UTF-8代码转换为符号字符

如何在python中将UTF-8代码转换为符号字符
EN

Stack Overflow用户
提问于 2015-01-23 06:43:16
回答 2查看 891关注 0票数 1

我使用python爬行了一些网页,并将读取的行保存到一个新文件中。

代码语言:javascript
运行
复制
        f = open(docId + ".html", "w+")
        with urllib.request.urlopen('http://stackoverflow.com') as u:
              s = u.read()
              f.write(str(s))

但是当我打开保存的文件时,我会看到许多字符串,比如\xe2\x86\x90,它最初是原始页面中的箭头符号。它似乎是一个符号的UTF-8代码,但我如何将代码转换回符号?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-01-23 14:04:08

您的代码坏了:u.read()返回bytes对象。str(bytes_object)返回对象的字符串表示(字节文本的样子) --您不希望它出现在这里:

代码语言:javascript
运行
复制
>>> str(b'\xe2\x86\x90')
"b'\\xe2\\x86\\x90'"

或者按如下方式将字节保存在磁盘上:

代码语言:javascript
运行
复制
import urllib.request

urllib.request.urlretrieve('http://stackoverflow.com', 'so.html')

或者以二进制模式打开文件:'wb'并手动保存:

代码语言:javascript
运行
复制
import shutil
from urllib.request import urlopen

with urlopen('http://stackoverflow.com') as u, open('so.html', 'wb') as file:
    shutil.copyfileobj(u, file)

或将字节转换为Unicode,并使用任何您喜欢的编码将它们保存到磁盘。

代码语言:javascript
运行
复制
import io
import shutil
from urllib.request import urlopen

with urlopen('http://stackoverflow.com') as u, \
     open('so.html', 'w', encoding='utf-8', newline='') as file, \
     io.TextIOWrapper(u, encoding=u.headers.get_content_charset('utf-8'), newline='') as t:
    shutil.copyfileobj(t, file)
票数 2
EN

Stack Overflow用户

发布于 2015-01-23 07:38:14

尝试:

代码语言:javascript
运行
复制
import urllib2, io

with io.open("test.html", "w", encoding='utf8') as fout:
    s = urllib2.urlopen('http://stackoverflow.com').read()
    s = s.decode('utf8', 'ignore') # or s.decode('utf8', 'replace')
    fout.write(s)

请参阅https://docs.python.org/2/howto/unicode.html

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28104377

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档