GVKun编程网logo

UnicodeEncodeError:'ascii'编解码器无法编码字符' xe9'--使用urlib.request python3时

20

对于UnicodeEncodeError:'ascii'编解码器无法编码字符'xe9'--使用urlib.requestpython3时感兴趣的读者,本文将会是一篇不错的选择,并为您提供关于nginx

对于UnicodeEncodeError:'ascii'编解码器无法编码字符' xe9'--使用urlib.request python3时感兴趣的读者,本文将会是一篇不错的选择,并为您提供关于nginx – uWSGI / Emperor:UnicodeEncodeError:’ascii’编解码器无法编码字符、Python 3 UnicodeEncodeError:’ascii’编解码器无法编码字符、python 3.2 UnicodeEncodeError:'charmap'编解码器无法在位置9629中编码字符' u2013':字符映射到、Python 3:os.walk()文件路径UnicodeEncodeError:'utf-8'编解码器无法编码:不允许代理的有用信息。

本文目录一览:

UnicodeEncodeError:'ascii'编解码器无法编码字符' xe9'--使用urlib.request python3时

UnicodeEncodeError:'ascii'编解码器无法编码字符' xe9'--使用urlib.request python3时

我正在编写一个脚本,该脚本转到链接列表并解析信息。

它适用于大多数站点,但在某些情况下令人“目结舌:“ UnicodeEncodeError:’ascii’编解码器无法在位置13编码字符’\
xe9’:序数不在范围(128)”

它在python3上urlib的client.py上停止

确切的链接是:http : //finance.yahoo.com/news/cafés-
growing-faster-than-fast-food-peers-144512056.html

这里有很多类似的帖子,但是似乎没有答案对我有用。

我的代码是:

from urllib import requestdef __request(link,debug=0):try:    html = request.urlopen(link, timeout=35).read() #made this long as I was getting lots of timeouts    unicode_html = html.decode(''utf-8'',''ignore'')# NOTE the except HTTPError must come first, otherwise except URLError will also catch an HTTPError.except HTTPError as e:    if debug:        print(''The server couldn\''t fulfill the request for '' + link)        print(''Error code: '', e.code)    return ''''except URLError as e:    if isinstance(e.reason, socket.timeout):        print(''timeout'')        return ''''    else:    return unicode_html

这调用了请求功能

链接=’ http: //finance.yahoo.com/news/cafés-
growing-faster-than-fast-food-peers-144512056.html’页面= __request(链接)

追溯是:

Traceback (most recent call last):  File "<string>", line 250, in run_nodebug  File "C:\reader\get_news.py", line 276, in <module>    main()  File "C:\reader\get_news.py", line 255, in main    body = get_article_body(item[''link''],debug=0)  File "C:\reader\get_news.py", line 155, in get_article_body    page = __request(''na'',url)  File "C:\reader\get_news.py", line 50, in __request    html = request.urlopen(link, timeout=35).read()  File "C:\Python33\Lib\urllib\request.py", line 156, in urlopen    return opener.open(url, data, timeout)  File "C:\Python33\Lib\urllib\request.py", line 469, in open    response = self._open(req, data)  File "C:\Python33\Lib\urllib\request.py", line 487, in _open    ''_open'', req)  File "C:\Python33\Lib\urllib\request.py", line 447, in _call_chain    result = func(*args)  File "C:\Python33\Lib\urllib\request.py", line 1268, in http_open    return self.do_open(http.client.HTTPConnection, req)  File "C:\Python33\Lib\urllib\request.py", line 1248, in do_open    h.request(req.get_method(), req.selector, req.data, headers)  File "C:\Python33\Lib\http\client.py", line 1061, in request    self._send_request(method, url, body, headers)  File "C:\Python33\Lib\http\client.py", line 1089, in _send_request    self.putrequest(method, url, **skips)  File "C:\Python33\Lib\http\client.py", line 953, in putrequest    self._output(request.encode(''ascii''))UnicodeEncodeError: ''ascii'' codec can''t encode character ''\xe9'' in position 13: ordinal not in range(128)

任何帮助表示赞赏它使我发疯,我想我已经尝试过x.decode和类似内容的所有组合

(如果可能的话,我可以忽略令人讨厌的字符。)

答案1

小编典典

使用百分比编码的网址:

link = ''http://finance.yahoo.com/news/caf%C3%A9s-growing-faster-than-fast-food-peers-144512056.html''

通过将浏览器指向,我找到了以上以百分比编码的网址

http://finance.yahoo.com/news/cafés-growing-faster-than-fast-food-peers-144512056.html

转到页面,然后将浏览器提供的编码的URL复制并粘贴回文本编辑器。但是,您可以使用以下方式以编程方式生成百分比编码的URL:

from urllib import parselink = ''http://finance.yahoo.com/news/cafés-growing-faster-than-fast-food-peers-144512056.html''scheme, netloc, path, query, fragment = parse.urlsplit(link)path = parse.quote(path)link = parse.urlunsplit((scheme, netloc, path, query, fragment))

产生

http://finance.yahoo.com/news/caf%C3%A9s-growing-faster-than-fast-food-peers-144512056.html

nginx – uWSGI / Emperor:UnicodeEncodeError:’ascii’编解码器无法编码字符

nginx – uWSGI / Emperor:UnicodeEncodeError:’ascii’编解码器无法编码字符

我在uwsgi / emeror / Nginx服务器上编码有很大问题.
我的应用程序开发为批处理excel文件处理.

我使用最新版本的烧瓶和烧瓶扩展,并使用flask-excel.

我的应用程序在Digital Ocean / ubuntu服务器上运行,我的配置文件是:

/etc/init/uwsgi.conf

description "uWsgi"
start on runlevel [2345]
stop on runlevel [06]
respawn

env UWsgi=/home/lukas/www/abissk/venv/bin/uwsgi
env LOGTO=/home/lukas/logs/abissk/emperor.log
exec $UWsgi --master --emperor /etc/uwsgi/vassals --die-on-term --uid www-data --gid www-data --logto $LOGTO  

/etc/uwsgi/vassals/abissk_uwsgi.ini

[uwsgi]
plugins = python
#pcre = True

#application's base folder
base = /home/lukas/www/abissk/

#enable-threads = true

#python module to import
app = wsgi
module = %(app) 

home = %(base)venv
pythonpath = %(base)

#socket file's location
socket = /home/lukas/www/abissk/%n.sock

#permissions for the socket file
chmod-socket = 644

#the variable that holds a flask application inside the module imported at line #6
callable = app

#location of log files
logto = /home/lukas/logs/abissk/%n.log

/home/lukas/www/abissk/wsgi.py

# -*- coding: utf-8 *-*
from app.app import create_app
from app.settings import ProdConfig

app = create_app(config_object=ProdConfig)

在/ etc / Nginx的/启用的站点 – / abissk_Nginx

server {
    listen 80;
    server_name benela.abis.sk; 
    charset     utf-8;
    client_max_body_size 75M;

    location / { try_files $uri @yourapplication; }
    location @yourapplication {
        include uwsgi_params;
        uwsgi_pass unix:/home/lukas/www/abissk/abissk_uwsgi.sock;
    }

}

这是我的问题:
使用命令启动应用程序时:

 ~/www/abissk/venv/bin/uwsgi --ini /etc/uwsgi/vassals/abissk_uwsgi.ini

并上传excel文件工作得很好但是

当使用emperor与完全相同的配置文件(在/etc/init/uwsgi.conf中)启动相同的应用程序时,应用程序工作正常,但是当上传excel文件到批处理时,我只看到消息:“502 Bad Gateway”并在我的日志中是:

 UnicodeEncodeError: 'ascii' codec can't encode character '\xfd' in position 31: ordinal not in range(128)

我尝试使用apt-get / pip3安装安装uwsgi并且场景相同:当没有皇帝直接运行应用程序时,工作正常;当使用emperor运行应用程序(具有相同配置)时,每个上传excel文件到我的应用程序以崩溃结束:/

谢谢你的回答

@H_301_63@
最佳答案@H_301_63@
将以下行添加到您的abissk_uwsgi.ini文件中以强制uwsgi使用UTF-8.

env LANG=en_US.utf8
env LC_ALL=en_US.UTF-8
env LC_LANG=en_US.UTF-8
@H_301_63@

总结

以上是小编为你收集整理的nginx – uWSGI / Emperor:UnicodeEncodeError:’ascii’编解码器无法编码字符全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

flask

Python 3 UnicodeEncodeError:’ascii’编解码器无法编码字符

Python 3 UnicodeEncodeError:’ascii’编解码器无法编码字符

我刚刚开始学习 Python,但我已经遇到了麻烦.
我有一个只有一个命令的简单脚本:
#!/usr/bin/env python3
print("Příliš žluťoučký kůň úpěl ďábelské ódy.") # Text in Czech

当我尝试运行此脚本时:

python3 hello.py

我收到这条消息:

Traceback (most recent call last):
  File "hello.py",line 2,in <module>
    print("P\u0159\xedli\u0161 \u017elu\u0165ou\u010dk\xfd k\u016fn \xfap\u011bl \u010f\xe1belsk\xe9 \xf3dy.")
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-2: ordinal not in range(128)

我正在使用Kubuntu 16.04和Python 3.5.2.
当我尝试这个:导出PYTHONIOENCODING = utf-8它只能暂时工作.下次我打开bash时遇到了同样的错误.

根据https://docs.python.org/3/howto/unicode.html#the-string-type
Python源代码的默认编码是UTF-8.
所以我把源文件保存为id UTF-8,Konsole设置为UTF-8但我仍然得到错误!
即使我补充说

# -*- coding: utf-8 -*-

从一开始它什么都不做.

另一个奇怪的事情:当我只使用python而不是python3运行它时,它可以工作.如何在Python 2.7.12中工作而不是在3.5.2中工作?

永久解决这个问题的任何想法?谢谢.

解决方法

感谢Mark Tolen和Alastair McCormack建议问题所在.问题出在区域设置中.
当我运行语言环境时,输出是:
LANG=C
LANGUAGE=
LC_CTYPE="C"
LC_NUMERIC=cs_CZ.UTF-8
LC_TIME=cs_CZ.UTF-8
LC_COLLATE=cs_CZ.UTF-8
LC_MONETARY=cs_CZ.UTF-8
LC_MESSAGES="C"
LC_PAPER="C"
LC_NAME="C"
LC_ADDRESS="C"
LC_TELEPHONE="C"
LC_MEASUREMENT=cs_CZ.UTF-8
LC_IDENTIFICATION="C"
LC_ALL=

此“C”是使用ANSI charmap的默认设置.这就是问题所在.运行locale charmap给了我:ANSI_X3.4-1968,它不能显示非英文字符.
我用这个Ubuntu documentation site解决了这个问题.

我将这些行添加到/ etc / default / locale:

LANGUAGE=cs_CZ.UTF-8
LC_ALL=cs_CZ.UTF-8

然后,您必须重新启动会话(注销并进入)才能应用这些设置.

运行语言环境现在返回此输出:

LANG=C
LANGUAGE=cs
LC_CTYPE="cs_CZ.UTF-8"
LC_NUMERIC="cs_CZ.UTF-8"
LC_TIME="cs_CZ.UTF-8"
LC_COLLATE="cs_CZ.UTF-8"
LC_MONETARY="cs_CZ.UTF-8"
LC_MESSAGES="cs_CZ.UTF-8"
LC_PAPER="cs_CZ.UTF-8"
LC_NAME="cs_CZ.UTF-8"
LC_ADDRESS="cs_CZ.UTF-8"
LC_TELEPHONE="cs_CZ.UTF-8"
LC_MEASUREMENT="cs_CZ.UTF-8"
LC_IDENTIFICATION="cs_CZ.UTF-8"
LC_ALL=cs_CZ.UTF-8

并运行locale charmap返回:

UTF-8

python 3.2 UnicodeEncodeError:'charmap'编解码器无法在位置9629中编码字符' u2013':字符映射到

python 3.2 UnicodeEncodeError:'charmap'编解码器无法在位置9629中编码字符' u2013':字符映射到

我正在尝试制作一个从sqlite3数据库中获取数据的脚本,但是遇到了问题。

数据库中的字段为text类型,并且包含html格式的文本。见下面的文字

<html><head><title>Yahoo!</title></head><body><style type="text/css">html {}.yshortcuts {border-bottom:none !important;}.ReadMsgBody {width:100%;}.ExternalClass{width:100%;}</style><table cellpadding="0" cellspacing="0" bgcolor="#ffffff">    <tr><td width="550" valign="top" align="left">    <table cellpadding="0" cellspacing="0" width="500">        <tr>            <td colspan="3"><img        src="http://mail.yimg.com/nq/assets/sharedmessages/v1/us/logo.gif" width="292" height="51"border="0" alt="Yahoo! Mail"></td>        </tr>        <tr>            <td rowspan="3" width="1" bgcolor="#c7c4ca"></td>            <td width="498" height="1" bgcolor="#c7c4ca"></td>            <td rowspan="3" width="1" bgcolor="#c7c4ca"></td>        </tr>        <tr>            <td width="498" valign="top" align="left">            <table cellpadding="0" cellspacing="0">                <tr>                    <td width="498" bgcolor="#61399d" align="left" valign="top">                    <table cellspacing="0" cellpadding="0"><tr><td height="24"></td></tr></table>                    <div><span>Välkommen till Yahoo! Mail.</span></div>                    <div>Ansluta och dela går snabbt och enkelt och är tillgängligt överallt.</div>                    </td>                </tr>                <tr>                    <td><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/b1.gif" width="498" height="18"border="0"></td>                </tr>            </table>            <table cellpadding="0" cellspacing="0" width="498">                <tr>                    <td width="292" valign="top">                    <table cellpadding="0" cellspacing="0">                        <tr>                            <td><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/grad.gif" width="292" height="9"></td>                        </tr>                        <tr>                            <td width="292" bgcolor="#ffffff" align="left" valign="top">                            <table cellspacing="0" cellpadding="0"><tr><td height="11"></td></tr></table>                            <div>                                                  <div>Det är lätt som en plätt att komma igång.</div>                                <table cellpadding="0" cellspacing="0" width="267">                                    <tr>                                        <td width="16" align="left" valign="top"><div>1. </div></td>                                        <td align="left" valign="top"><div><a rel="nofollow" target="_blank" href="http://us-mg999.mail.yahoo.com/neo/launch?action=contacts"><span>Lägg till alla dina kontakter på en plats</span></a>.</div></td>                                    </tr>                                    <tr>                                        <td align="left" valign="top"><div>2. </div></td>                                        <td align="left" valign="top"><div><a rel="nofollow" target="_blank" href="http://mrd.mail.yahoo.com/themes"><span>Anpassa din nya inkorg</span></a>.</div></td>                                    </tr>                                    <tr>                                        <td align="left" valign="top"><div>3. </div></td>                                        <td align="left" valign="top"><div><a rel="nofollow" target="_blank" href="http://se.overview.mail.yahoo.com/mobile"><span>Anslut överallt på dina mobila enheter</span></a>.</div></td>                                    </tr>                                </table>                            </div>                            </td>                        </tr>                        <tr><td height="13"></td></tr>                    </table>                    </td>                    <td width="196" valign="top">                    <table cellpadding="0" cellspacing="0">                        <tr>                            <td width="1" bgcolor="#fbfbfd" valign="top"><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/g1.gif" width="1" height="21"></td>                            <td width="1" bgcolor="#f5f6fa" valign="top"><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/g2.gif" width="1" height="21"></td>                            <td width="1" bgcolor="#e8eaf1" valign="top"><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/g3.gif" width="1" height="21"></td>                            <td width="1" bgcolor="#d4d4d4"></td>                            <td width="186" bgcolor="#f0f0f0" align="left" valign="top">                              <table cellspacing="0" cellpadding="0"><tr><td height="3">   </td></tr></table>                            <div>                            <div><b>Info för dig:</b></div>                            <div>                            Yahoo!-ID och e-postadress:<br />                            <div>                            Håll ditt konto och inställningar aktuella. <br><a rel="nofollow" target="_blank" href="https://edit.yahoo.com/config/eval_profile"><span>Mitt konto</span></a>                             </div>                            </div>                            <table cellspacing="0" cellpadding="0"><tr><td height="20"></td></tr></table>                            </td>                            <td width="1" bgcolor="#dbdbdb"></td>                            <td width="1" bgcolor="#ced2de"></td>                            <td width="1" bgcolor="#dbdfed"></td>                            <td width="1" bgcolor="#e8ebf3"></td>                            <td width="1" bgcolor="#f3f4f9"></td>                            <td width="1" bgcolor="#fafbfc"></td>                        </tr>                        <tr>                            <td colspan="11"><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/b2.gif" width="196" height="8"border="0"></td>                        </tr>                        <tr><td height="13"></td></tr>                    </table>                    </td>                    <td width="10"></td>                </tr>            </table>            </td>        </tr>        <tr>            <td width="498" height="1" bgcolor="#c7c4ca"></td>        </tr>    </table>    <table cellpadding="0" cellspacing="0" width="500">        <tr>            <td align="center" valign="top">            <table cellspacing="0" cellpadding="0"><tr><td height="10"></td></tr></table>                <div>                <a rel="nofollow" target="_blank" href="http://info.yahoo.com/legal/se/yahoo/utos.html">Yahoo! Villkor för användning</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;<a rel="nofollow" target="_blank" href="http://info.yahoo.com/legal/se/yahoo/mail/atos.html">Yahoo! Mail –Villkor för användning</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;<a rel="nofollow" target="_blank" href="http://info.yahoo.com/privacy/se/yahoo/details.html">Yahoo! Sekretesspolicy</a>                </div>            </td>        </tr>        <tr>            <td align="left" valign="top">                <div>Var god svara inte på detta meddelande. Detta är ett servicemeddelande som rör din användning av Yahoo! Mail. Om du vill veta mer om Yahoo!s användning av personlig information, inklusive användning av webb-beacons i HTML-baserad e-post, kan du läsa vår Yahoo! Sekretesspolicy. Yahoo!s adress är 701 First Avenue, Sunnyvale, CA 94089, USA.<br /><br />RefID: lp-1037111</div>            </td>        </tr>    </table>    </td></tr></table><img width="1" height="1" src="http://pclick.internal.yahoo.com/p/s=2143684696"></body></html>`

尝试提取数据的python代码如下。

>>> import sqlite3>>> conn = sqlite3.connect(''C:/temp/Mobils/export/com.yahoo.mobile.client.android.mail/databases/mail.db'')>>> c = conn.cursor()>>> conn.row_factory=sqlite3.Row>>> c.execute(''select body from messages_1 where _id=7'')<sqlite3.Cursor object at 0x0000000001FB78F0>>>> r = c.fetchone()>>> r.keys()[''body'']>>> print(r[''body''])Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "C:\Python32\lib\encodings\cp850.py", line 19, in encode    return codecs.charmap_encode(input,self.errors,encoding_map)[0]UnicodeEncodeError: ''charmap'' codec can''t encode character ''\u2013'' in position 9629: character maps to <undefined>>>>

是否有人对如何将其打印/写入文件有任何想法。是的,我知道这是打印到stdout的,但是当我尝试写入文件时会出现相同的UnicodeEncodeError。我尝试了文件对象的写入方法和print(r[''body''],file=f)

答案1

小编典典

当您打开要写入的文件时,请使用可以处理所有字符的特定编码打开它。

with open(''filename'', ''w'', encoding=''utf-8'') as f:    print(r[''body''], file=f)

Python 3:os.walk()文件路径UnicodeEncodeError:'utf-8'编解码器无法编码:不允许代理

Python 3:os.walk()文件路径UnicodeEncodeError:'utf-8'编解码器无法编码:不允许代理

如何解决Python 3:os.walk()文件路径UnicodeEncodeError:''utf-8''编解码器无法编码:不允许代理?

在Linux上,文件名只是“一堆字节”,不一定以特定的编码进行编码。Python 3尝试将所有内容转换为Unicode字符串。通过这样做,开发人员想出了一种方案,可以将字节字符串转换为Unicode字符串,然后又将其转换回去而不会丢失,也不会知道原始编码。他们使用部分替代来编码“坏”字节,但是普通的UTF8编码器在打印到终端时无法处理它们。

例如,这是一个非UTF8字节的字符串:

>>> b''C\xc3N''.decode(''utf8'',''surrogateescape'')
''C\udcc3N''

它可以与Unicode相互转换而不会丢失:

>>> b''C\xc3N''.decode(''utf8'',''surrogateescape'').encode(''utf8'',''surrogateescape'')
b''C\xc3N''

但是无法打印:

>>> print(b''C\xc3N''.decode(''utf8'',''surrogateescape''))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: ''utf-8'' codec can''t encode character ''\udcc3'' in position 1: surrogates not allowed

您必须弄清楚要使用非默认编码的文件名要做什么。也许只是将它们编码回原始字节,然后用未知替换将其解码。使用它进行显示,但保留原始名称以访问文件。

>>> b''C\xc3N''.decode(''utf8'',''replace'')
C�N

os.walk 也可以采用字节字符串,并返回字节字符串而不是Unicode字符串:

for p,d,f in os.walk(b''.''):

然后,您可以根据需要进行解码。

解决方法

这段代码:

for root,dirs,files in os.walk(''.''):
    print(root)

给我这个错误:

UnicodeEncodeError: ''utf-8'' codec can''t encode character ''\udcc3'' in position 27: surrogates not allowed

如何遍历文件树而不会得到像这样的有害字符串?

关于UnicodeEncodeError:'ascii'编解码器无法编码字符' xe9'--使用urlib.request python3时的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于nginx – uWSGI / Emperor:UnicodeEncodeError:’ascii’编解码器无法编码字符、Python 3 UnicodeEncodeError:’ascii’编解码器无法编码字符、python 3.2 UnicodeEncodeError:'charmap'编解码器无法在位置9629中编码字符' u2013':字符映射到、Python 3:os.walk()文件路径UnicodeEncodeError:'utf-8'编解码器无法编码:不允许代理等相关知识的信息别忘了在本站进行查找喔。

本文标签: