如何解决编码在Python机械化?(How to fix encoding in Python Me

2019-08-17 08:22发布

这里是示例代码:

from mechanize import Browser

br = Browser()
page = br.open('http://hunters.tclans.ru/news.php?readmore=2')
br.form = br.forms().next()
print br.form

问题是,服务器返回不正确的编码(Windows的CP1251)。 我如何可以手动设置在机械化当前页面的编码?

错误:

Traceback (most recent call last):
  File "/tmp/stackoverflow.py", line 5, in <module>
    br.form = br.forms().next()
  File "/usr/local/lib/python2.6/dist-packages/mechanize/_mechanize.py", line 426, in forms
    return self._factory.forms()
  File "/usr/local/lib/python2.6/dist-packages/mechanize/_html.py", line 559, in forms
    self._forms_factory.forms())
  File "/usr/local/lib/python2.6/dist-packages/mechanize/_html.py", line 225, in forms
    _urlunparse=_rfc3986.urlunsplit,
  File "/usr/local/lib/python2.6/dist-packages/ClientForm.py", line 967, in ParseResponseEx
    _urlunparse=_urlunparse,
  File "/usr/local/lib/python2.6/dist-packages/ClientForm.py", line 1104, in _ParseFileEx
    fp.feed(data)
  File "/usr/local/lib/python2.6/dist-packages/ClientForm.py", line 870, in feed
    sgmllib.SGMLParser.feed(self, data)
  File "/usr/lib/python2.6/sgmllib.py", line 104, in feed
    self.goahead(0)
  File "/usr/lib/python2.6/sgmllib.py", line 193, in goahead
    self.handle_entityref(name)
  File "/usr/local/lib/python2.6/dist-packages/ClientForm.py", line 751, in handle_entityref
    '&%s;' % name, self._entitydefs, self._encoding))
  File "/usr/local/lib/python2.6/dist-packages/ClientForm.py", line 238, in unescape
    return re.sub(r"&#?[A-Za-z0-9]+?;", replace_entities, data)
  File "/usr/lib/python2.6/re.py", line 151, in sub
    return _compile(pattern, 0).sub(repl, string, count)
  File "/usr/local/lib/python2.6/dist-packages/ClientForm.py", line 230, in replace_entities
    repl = repl.encode(encoding)
LookupError: unknown encoding: windows-cp1251

Answer 1:

我不知道机械化,但你可以砍codecs接受兼得“窗口” “CP”错误的编码名称:

>>> def fixcp(name):
...     if name.lower().startswith('windows-cp'):
...         try:
...             return codecs.lookup(name[:8]+name[10:])
...         except LookupError:
...             pass
...     return None
... 
>>> codecs.register(fixcp)
>>> '\xcd\xe0\xef\xee\xec\xe8\xed\xe0\xe5\xec'.decode('windows-cp1251')
u'Напоминаем'


Answer 2:

通过设置固定

br._factory.encoding = enc
br._factory._forms_factory.encoding = enc
br._factory._links_factory._encoding = enc

(注意下划线)br.open后()



文章来源: How to fix encoding in Python Mechanize?