title: Python判断网页编码
copyright: true
top: 0
date: 2018-05-04 17:37:58
tags: 基础
categories: 爬虫笔记
permalink:
password:
keywords: [Python爬虫,编码]
description: 做爬虫或者测试的时候,返回网页的编码是个很让人头疼的问题,这篇文章做个网页编码问题解决方法总结。
有一种渴,只有酒才能滋润,这种渴就是孤独。
根据网页返回编码寻找数据
比如我要找到这个网页的标题,那么直接正则匹配
解决办法:
r_port_top = requests.get(url=str('http://'+url), headers=headers, timeout=5)
if r_port_top.encoding == 'ISO-8859-1':
encodings = requests.utils.get_encodings_from_content(r_port_top.text)
if encodings:
encoding = encodings[0]
else:
encoding = r_port_top.apparent_encoding
encode_content = r_port_top.content.decode(encoding, 'replace').encode('utf-8', 'replace')
port_title = re.search('<title>(.*?)</title>', encode_content, re.S).group().replace('<title>',
'').replace(
'</title>', '')
这种办法就是先判断网页的编码,然后转换之。但是有的时候是utf-8编码就没办法,接下来来个终极版的。
try:
UA = random.choice(headerss)
headers = {'User-Agent': UA}
r_port_top = requests.get(url=str('http://'+url), headers=headers, timeout=5)
if r_port_top.encoding == 'ISO-8859-1':
encodings = requests.utils.get_encodings_from_content(r_port_top.text)
if encodings:
encoding = encodings[0]
else:
encoding = r_port_top.apparent_encoding
encode_content = r_port_top.content.decode(encoding, 'replace').encode('utf-8', 'replace')
port_title = re.search('<title>(.*?)</title>', encode_content, re.S).group().replace('<title>',
'').replace(
'</title>', '')
e