[英]Python encoding unicode utf-8
我正在使用硒在Web公式中插入带有德国变音符号的文本输入。 python脚本的声明编码为utf-8。 该页面使用utf-8编码。 当我定义这样的字符串时,一切正常:
q = u"Hällö" #type(q) returns unicode
...
textbox.send_keys(q)
但是,当我尝试使用ConfigParser(或另一种文件)读取配置文件时,我在webformular( Hällö
)中得到了格式错误的输出。 这是我使用的代码:
the_encoding = chardet.detect(q)['encoding'] #prints utf-8
q = parser.get('info', 'query') # type(q) returns str
q = q.decode('unicode-escape') # type(q) returns unicode
textbox.send_keys(q)
给send_keys函数的两个q之间有什么区别?
这可能是错误的编码。 尝试在最后一条语句前打印q
,看是否相等。 这行q = parser.get('info', 'query') # type(q) returns str
应该返回字符串'H\\xc3\\xa4ll\\xc3\\xb6'
。 如果不同,则说明您使用了错误的编码。
>>> q = u"Hällö" # unicode obj
>>> q
u'H\xe4ll\xf6'
>>> print q
Hällö
>>> q.encode('utf-8')
'H\xc3\xa4ll\xc3\xb6'
>>> a = q.encode('utf-8') # str obj
>>> a
'H\xc3\xa4ll\xc3\xb6' # <-- this should be the value of the str
>>> a.decode('utf-8') # <-- unicode obj
u'H\xe4ll\xf6'
>>> print a.decode('utf-8')
Hällö
>>>
from ConfigParser import SafeConfigParser
import codecs
parser = SafeConfigParser()
with codecs.open('cfg.ini', 'r', encoding='utf-8-sig') as f:
parser.readfp(f)
greet = parser.get('main', 'greet')
print 'greet:', greet.encode('utf-8-sig')
问候:哈洛
cfg.ini文件
[main]
greet=Hällö
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.