网页抓取解密( Python页面抓取过程中乱码的原因与相应的解决方法)
优采云 发布时间: 2021-10-02 19:02网页抓取解密(
Python页面抓取过程中乱码的原因与相应的解决方法)
python抓取并保存html页面时出现乱码问题的解决方法
更新时间:2016-07-01 11:23:47 作者:holybin
本文文章主要介绍了python爬取html页面时出现乱码问题的解决方法,并结合示例表单分析了python页面爬取过程中出现乱码的原因及相应的解决方法。有需要的朋友可以参考Down
本文示例介绍了python抓取并保存html页面时出现乱码问题的解决方法。分享给大家,供大家参考,如下:
使用Python抓取html页面并保存时,经常会出现抓取页面内容乱码的问题。出现这个问题的原因,一方面是代码中的编码设置有问题;另一方面,当编码设置正确时,网页的实际编码与标记的编码不匹配。html页面上标注的代码在这里:
复制代码代码如下:
这里有一个简单的解决方法:使用chardet来判断网页的真实编码,同时从url请求返回的info中判断出mark编码。如果两种编码不同,使用bs模块扩展为GB18030编码;如果相同,直接写入文件(这里设置系统默认编码为utf-8)。
import urllib2
import sys
import bs4
import chardet
reload(sys)
sys.setdefaultencoding('utf-8')
def download(url):
htmlfile = open('test.html','w')
try:
result = urllib2.urlopen(url)
content = result.read()
info = result.info()
result.close()
except Exception,e:
print 'download error!!!'
print e
else:
if content != None:
charset1 = (chardet.detect(content))['encoding'] #real encoding type
charset2 = info.getparam('charset') #declared encoding type
print charset1,' ', charset2
# case1: charset is not None.
if charset1 != None and charset2 != None and charset1.lower() != charset2.lower():
newcont = bs4.BeautifulSoup(content, from_encoding='GB18030') #coding: GB18030
for cont in newcont:
htmlfile.write('%s\n'%cont)
# case2: either charset is None, or charset is the same.
else:
#print sys.getdefaultencoding()
htmlfile.write(content) #default coding: utf-8
htmlfile.close()
if __name__ == "__main__":
url = 'https://www.jb51.net'
download(url)
获取到的test.html文件打开如下,可以看到它是以UTF-8无BOM编码格式存储的,也就是我们设置的默认编码:
对Python相关内容感兴趣的读者可以查看本站专题:《Python编码操作技巧总结》、《Python图片操作技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》 ,《Python函数使用技巧总结》、《Python字符串操作技巧总结》、《Python入门及进阶经典教程》、《Python文件与目录操作技巧总结》
我希望这篇文章对你的 Python 编程有所帮助。