1

It is a very strange error, let's see detail:

ts.py file:

#-*- coding: utf-8 -*-
import requests
from lxml import html

headers = {
          'Host':'www.baidu.com',
          'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36',
          }

def get_html(url,enable_proxy=None):
    r = requests.get(url,headers=headers)
    parser = html.HTMLParser(encoding='utf-8')
    return html.document_fromstring(r.text, parser=parser)

p = get_html('http://www.baidu.com')

print p.xpath(u'//*[@id="setf"]/text()')[0].encode('utf-8')

If I just execute ts.py, lxml works perfect.

But!Error comes up when I put get_html in another file, see follow:

ts.py:

#-*- coding: utf-8 -*-
import requests
from util import get_html

p = get_html('http://www.baidu.com')
print p.xpath(u'//*[@id="setf"]/text()')[0].encode('utf-8')

util.py:

#-*- coding: utf-8 -*-
import requests
from lxml import html

headers = {
          'Host':'www.baidu.com',
          'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.72 Safari/537.36',
          }

def get_html(url, enable_proxy=None):
    r = requests.get(url,headers=headers)
    parser = html.HTMLParser(encoding='uft-8')
    return html.document_fromstring(r.text, parser=parser)

tun ts.py output:

Traceback (most recent call last):
  File "C:\Users\mithril\Desktop\1\ts.py", line 8, in <module>
    p = get_html('http://www.baidu.com')
  File "C:\Users\mithril\Desktop\1\util.py", line 15, in get_html
    parser = html.HTMLParser(encoding='uft-8')
  File "E:\Python27\lib\site-packages\lxml\html\__init__.py", line 1662, in __init__
    super(HTMLParser, self).__init__(**kwargs)
  File "parser.pxi", line 1597, in lxml.etree.HTMLParser.__init__ (src\lxml\lxml.etree.c:99825)
  File "parser.pxi", line 792, in lxml.etree._BaseParser.__init__ (src\lxml\lxml.etree.c:92549)
LookupError: unknown encoding: 'uft-8'

My environment:

  • Windows 7 x64
  • Python 2.7
  • lxml‑3.3.1 from here

I test python 2.7 32 bit and 64 bit both, same result.

1
  • uft-8 is not an encoding. utf-8 is though.
    – aquavitae
    Apr 10, 2014 at 8:08

1 Answer 1

15

There is typo: should be utf-8 not uft-8:

#parser = html.HTMLParser(encoding='uft-8')
parser = html.HTMLParser(encoding='utf-8')
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.