首页 > beautifulsoup解析中文网页的编码问题

beautifulsoup解析中文网页的编码问题

对于同一个页面,几乎同样的代码,在Python3,windows8环境下能够正常解析运行。但是把代码移植到Ubuntu,Python2.7下面之后,会出现获取的网页不能被beautifulsoup解析,find_all('table')返回空节点的情况。
出问题的代码的一部分(可以运行):

python#coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import urllib2
from bs4 import BeautifulSoup
postdata = "T1=&T2=1&T3=&T4=&T5=&APPDate=&T7=&T8=&T9=&PRDate=&T11=&SQDate=&JDDate=&T14=&T15=&T16=&T17=&SDDate=&T19=&T20=&T21=&D1=%B8%B4%C9%F3&D2=jdr&D3=%C9%FD%D0%F2&C1=fm&C2=&C3=&page=70"
postdata = postdata.encode('utf-8')
headers = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6','Referer':'http://app.sipo-reexam.gov.cn/reexam_out/searchdoc/searchfs.jsp'}
req = urllib2.Request(
      url = "http://app.sipo-reexam.gov.cn/reexam_out/searchdoc/searchfs.jsp",
      headers = headers,
      data = postdata)
fp  = urllib2.urlopen(req)
mybytes = fp.read().decode('gbk').encode('utf-8')
soup = BeautifulSoup(mybytes,from_coding="uft-8")
print soup.original_encoding
print soup.prettify()

求指点一二


有没有尝试过换一个解析器。
python2.7的html解析器容错率很差。
推荐lxml。


呃,这个主要是编码问题。。。python的encoding问题没弄明白绝对是个大坑。
我看到这几句话,好像都有点问题:

1. mybytes = fp.read().decode('gbk').encode('utf-8')
2. soup = BeautifulSoup(mybytes,from_coding="uft-8")
3. print soup.original_encoding
4. print soup.prettify()

其中,

  1. 不需要编码转换,bs可以接受任何编码,unicode更好。所以即使编码转换也应该只到decode就够了

  2. bs实例构造用法是BeautifulSoup(html, 'html5lib'),第二个参数是解释器,而不是编码。

  3. 直接print soup就能出结果啦,显不显示中文主要和编码有关,bs的编码转换能力其实还是不那么强的,所以明文调用也会出问题

  4. soup.prettify('utf-8')这样的才能保证输出的编码正确。

【热门文章】
【热门文章】