Python 网页解析笔记(一)

语言版本:Python 2.7

函数库:urllib2、chardet、BeautifulSoup

示例代码如下:

import urllib2
import chardet
from bs4 import BeautifulSoup

data = urllib2.urlopen('http://www.nitrohsu.com').read()
encodeStr = chardet.detect(a)['encoding']
soup=BeautifulSoup(data,from_encoding=encodeStr)

print soup.prettify


chardet是一个自动检测网页编码的函数,调用detect会返回一个字典:

{'confidence': 0.99, 'encoding': 'utf-8'}

confidence是检测的正确率,encoding是网页编码的代码


在BeautifulSoup4之后构造函数的fromEncoding参数改为from_encoding,当然用前者也可以,只是出现警告而已。


在Python内部都是按照unicode来编码的,所以在获取一个非unicode编码的网页时首先要将编码转换如decode('gbk'),是将GBK转换为UTF-8编码。


Windows CMD下需要将代码页改为65001才支持UTF-8。但是在使用BeautifulSoup的时候在命令行回显时会出现IOError,但在Python IDE下没有问题。