最近,我尝试使用urllib2和BeautifulSoup来提取一些网页的源码,但是由于错误代码的输出而失败。脚本如下所示(在Python IDLE中运行)
import urllib2
from bs4 import BeautifulSoup
web = "http://www.qq.com"
page = urllib2.urlopen(web)
soup = BeautifulSoup(page, "html.parser")
print soup.prettify()我发现"http://www.qq.com“的字符集是gb2312,所以在上面的脚本中添加了如下内容:
import urllib2
from bs4 import BeautifulSoup
web = "http://www.qq.com"
page = urllib2.urlopen(web)
soup = BeautifulSoup(page, "html.parser", from_encoding="gb2312")
print soup.prettify()但结果是令人沮丧的。有没有可用的解决方案?
错误消息的屏幕截图:
上周末,我在上面的代码中添加了模块sys,但它没有打印任何内容,这次没有任何警告。
#coding=utf-8
import urllib2
from bs4 import BeautifulSoup
import sys
reload(sys)
sys.setdefaultencoding('gbk')
web = "http://www.qq.com"
page = urllib2.urlopen(web)
soup = BeautifulSoup(page, "html.parser")
print soup.prettify()发布于 2015-11-26 13:58:21
你能发布错误信息吗?或者问题是它只是不能在屏幕上显示中文字符?
尝试切换到gb18030编码。尽管页面上说它的字符集是gb2313,但肯定有一个字符扰乱了解码。切换编码将我的终端输出从垃圾转换为中文字符(Source)
import urllib2
from bs4 import BeautifulSoup
web = "http://www.qq.com"
page = urllib2.urlopen(web)
soup = BeautifulSoup(page, "html.parser", from_encoding="gb18030")
print soup.prettify()https://stackoverflow.com/questions/33931157
复制相似问题