php网页抓取乱码(想了解python抓取并保存html页面时乱码问题的解决办法的相关内容吗)
优采云 发布时间: 2021-11-02 11:15php网页抓取乱码(想了解python抓取并保存html页面时乱码问题的解决办法的相关内容吗)
想知道python抓取保存html页面时出现乱码问题的解决方法相关内容吗?在本文中,holybin将仔细讲解python抓取保存html页面时出现乱码问题的相关知识和一些代码示例。欢迎阅读并指正,先重点介绍:python,抓取,保存,html页面,乱码,解决方法,一起学习。
本文示例介绍了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 = '//www.qb5200.com'
download(url)
获取到的test.html文件打开如下,可以看到它是以UTF-8无BOM编码格式存储的,也就是我们设置的默认编码:
我希望这篇文章对你的 Python 编程有所帮助。
相关文章