from urllib.request import urlopen
textPage = urlopen("https://fengshenfeilian.github.io/")
print(textPage.read())
在非纯英文网页上爬取数据时,总是会出现各种意想不到的乱码。
比如上文的代码运行结果含有中文,且所有中文都被替换成乱码。
这个问题是因为python默认的把文本读成ascII
在这里我们要是用UTF-8编码格式,就可以把一切字符正常的显示了
上文代码改成:
from urllib.request import urlopen
textPage = urlopen("https://fengshenfeilian.github.io/")
print(str(textPage.read(),'utf-8'))
显示结果完全正确
用BeautifulSoup 和Python 3.x 对文档进行UTF-8 编码,如下所示:
html = urlopen("https://fengshenfeilian.github.io/")
bsObj = BeautifulSoup(html)
content = bsObj.find("div", {"id":"mw-content-text"}).get_text()
content = bytes(content, "UTF-8")
content = content.decode("UTF-8")
你可能打算以后用网络爬虫的时候全部采用UTF-8 编码读取内容,毕竟UTF-8 也可以完美地处理ASCII 编码。但是,要记住还有9% 的网站使用I