libxml for python's utf encoding issue or mine?
hi all I'm trying to extract the "META" description from a webpage using libxml for python. When it encounters UTF chars it seems to choke and display garbage chars. However when getting the data via a regex I get the unicode chars just fine. Am I doing something wrong with libxml?
thanks
''' test encoding issues with utf8 '''
from lxml.html import fromstring
from lxml.html.clean import Cleaner
import urllib2
import re
url = 'http://www.youtube.com/watch?v=LE-JN7_rxtE'
page = urllib2.urlopen(url).read()
xmldoc = fromstring(page)
desc = xmldoc.xpath('/html/head/meta[@name="description"]/@content')
meta_description = desc[0].strip()
print "**** LIBXML TEST ****\n"
print meta_desc开发者_运维技巧ription
print "**** REGEX TEST ******"
reg = re.compile(r'<meta name="description" content="(.*)">')
for desc in reg.findall(page):
print desc
OUTPUTS:
**** LIBXML TEST ****
My name is Hikakin.<br>I'm Japanese Beatboxer.<br><br>HIKAKIN Official Blog<br>http://ameblo.jp/hikakin/<br><br>ãã³çã³ãã¥<br>http://com.nicovideo.jp/community/co313576<br><br>â»å¾¡ç¨ã®æ¹ã¯Youtubeã®ã¡ãã»ã¼ã¸ã¾ã...
**** REGEX TEST ******
My name is Hikakin.<br>I'm Japanese Beatboxer.<br><br>HIKAKIN Official Blog<br>http://ameblo.jp/hikakin/<br><br>ニコ生コミュ<br>http://com.nicovideo.jp/community/co313576<br><br>※御用の方はYoutubeのメッセージまた...
Does this help?
xmldoc = fromstring(page.decode('utf-8'))
It is very possible that the problem is that your console does not support the display of Unicode characters. Try piping the output to a file and then open it in something that can display Unicode.
In lxml, you need to pass the encoding to the parser. For HTML/XML parsing:
url = 'http://en.wikipedia.org/wiki/' + wiki_word
parser = lxml.etree.HTMLParser(encoding='utf-8') # you can either use an XMLParser()
page = urllib2.urlopen(url)
doc = etree.parse(page, parser)
T = doc.xpath('//p//text()')
text = u''.join(T).encode('utf-8')
精彩评论