刘伟

刘伟的博客

他的个人主页  他的博客

靓女比“靓汤”好搞(记BeautifulSoup的一个pitfall)

刘伟  2010年05月02日 星期日 12:56 | 1739次浏览 | 0条评论

昨天我从网上下载一个utf8的网页
用BeautifulSoup做了一点处理:sth like: soup.find('a').string ...
最后用django的orm保存到utf8 char set的mysql数据库中居然报了一个UnicodeEncodeError

在存的时候做了smart_unicode处理依然报错

找“靓汤”文档发现他信誓旦旦:

Beautiful Soup Gives You Unicode, Dammit

By the time your document is parsed, it has been transformed into Unicode. Beautiful Soup stores only Unicode strings in its data structures.

  
   from BeautifulSoup import BeautifulSoup
  
  
soup = BeautifulSoup("Hello")
soup.contents[0]
# u'Hello'
soup.originalEncoding
# 'ascii'

Django的文档也说:
Django natively supports Unicode data everywhere. Providing your database can somehow store the data, you can safely pass around Unicode strings to templates, models and the database.
  没办法了,只好到ipython里一步一步看他们的type,
  
最后发现
>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup('<div>i am beautiful</div>')
>>> soup.find('div').string
u'i am beautiful'
>>> type(soup.find('div').string)
<class 'BeautifulSoup.NavigableString'>

没错!虽然NavigableString是从unicode中继承而来,但是他也继承了PageElement
而django的smart_unicode并不会把NavigableString转换成基本的unicode类型,
于是在django存数据库时发生了错误,这个错误的原因我懒得去挖掘,希望有同学指点

只要把NavigableString转换成基本的unicode,就可以用Django ORM存数据库了

评论

我的评论:

发表评论

请 登录 后发表评论。还没有在Zeuux哲思注册吗?现在 注册 !

暂时没有评论

Zeuux © 2024

京ICP备05028076号