【发布时间】:2016-02-29 02:35:09
【问题描述】:
最近我尝试使用 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()
【问题讨论】:
标签: python-2.7 web-scraping beautifulsoup urllib2