如何在python的碎片中编码字符?



我使用splinter为一个网站做功能测试。只要我不输入特殊字符,测试就可以运行得很好,就像German Umlaute一样。

我如何调整脚本来测试这些字符的条目?

这是我到目前为止所尝试的:

# coding=utf-8
from splinter import Browser

URL = "http://www.example.com"
USER = raw_input("Username, please: ") # f.e. "Günther"
with Browser('') as browser:
    # Log in as administrator
    browser.visit(URL)
browser.fill('user', USER)

这是我得到的错误日志:

Traceback (most recent call last):
  File "test.py", line 47, in <module>
    browser.fill('user', USER)
  File "C:Python27libsite-packagessplinterdriverwebdriver__init__.py", line 230, in fill
    field.value = value
  File "C:Python27libsite-packagessplinterdriverwebdriver__init__.py", line 338, in _set_value
    self._element.send_keys(value)
  File "C:Python27libsite-packagesseleniumwebdriverremotewebelement.py", line 293, in send_keys
    self._execute(Command.SEND_KEYS_TO_ELEMENT, {'value': typing})
  File "C:Python27libsite-packagesseleniumwebdriverremotewebelement.py", line 370, in _execute
    return self._parent.execute(command, params)
  File "C:Python27libsite-packagesseleniumwebdriverremotewebdriver.py", line 164, in execute
    response = self.command_executor.execute(driver_command, params)
  File "C:Python27libsite-packagesseleniumwebdriverremoteremote_connection.py", line 344, in execute
    data = utils.dump_json(params)
  File "C:Python27libsite-packagesseleniumwebdriverremoteutils.py", line 30, in dump_json
    return json.dumps(json_struct)
  File "C:Python27libjson__init__.py", line 243, in dumps
    return _default_encoder.encode(obj)
  File "C:Python27libjsonencoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "C:Python27libjsonencoder.py", line 270, in iterencode
    return _iterencode(o, 0)
UnicodeDecodeError: 'utf8' codec can't decode byte 0x81 in position 0: invalid start byte

指定USER为unicode对象:

USER = u"Günther"
       ^

如果字符串来自外部源,解码它:

USER = USER.decode('<ENCODING-OF-THE-STRING>')

unidcode是我见过的最简洁的unicode处理程序。

相关内容

  • 没有找到相关文章

最新更新