处理BeautifulSoup中的印度语言

时间:2013-01-19 09:24:33

标签: python web-scraping beautifulsoup

我正试图抓取NDTV网站上的新闻标题。 This是我用作HTML源代码的页面。我正在使用BeautifulSoup(bs4)来处理HTML代码,我已经完成了所有工作,除了我在我链接到的页面中遇到hindi标题时代码中断。

到目前为止我的代码是:

import urllib2
from bs4 import BeautifulSoup

htmlUrl = "http://archives.ndtv.com/articles/2012-01.html"
FileName = "NDTV_2012_01.txt"

fptr = open(FileName, "w")
fptr.seek(0)

page = urllib2.urlopen(htmlUrl)
soup = BeautifulSoup(page, from_encoding="UTF-8")

li = soup.findAll( 'li')
for link_tag in li:
   hypref = link_tag.find('a').contents[0]
   strhyp = str(hypref)
   fptr.write(strhyp)
   fptr.write("\n")

我得到的错误是:

Traceback (most recent call last):
  File "./ScrapeTemplate.py", line 30, in <module>
  strhyp = str(hypref)
  UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)

即使我没有包含from_encoding参数,我也收到了同样的错误。我最初使用它作为fromEncoding,但python警告我,它已被弃用。

我该如何解决这个问题?从我所读到的,我需要避免印地文标题或明确编码为非ascii文本,但我不知道如何做到这一点。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:3)

你看到的是一个NavigableString实例(它是从Python unicode类型派生的):

(Pdb) hypref.encode('utf-8')
'NDTV'
(Pdb) hypref.__class__
<class 'bs4.element.NavigableString'>
(Pdb) hypref.__class__.__bases__
(<type 'unicode'>, <class 'bs4.element.PageElement'>)

您需要使用

转换为utf-8
hypref.encode('utf-8')

答案 1 :(得分:1)

strhyp = hypref.encode('utf-8')

http://joelonsoftware.com/articles/Unicode.html