python BeautifulSoup设置页面编码的方法

WBOY
Release: 2016-06-10 15:16:24
Original
1390 people have browsed it

在用BeautifulSoup进行抓取页面的时候,会各种各样的编码错误。
可以通过在beautifulsoup中指定字符编码,解决问题。

复制代码 代码如下:

import urllib2 
from BeautifulSoup import BeautifulSoup 
 
page = urllib2.urlopen('http://www.163.com'); 
soup = BeautifulSoup(page,from_encoding="gb2312") 
 
print soup.originalEncoding
print soup.prettify() 

红色部分表示需要注意的地方。在BeautifulSoup构造器中传入fromEncoding参数即可解决乱码问题,当然具体参数值是什么就要看你获取页面的编码是什么
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template