检测网页编码+读取网页内容

import chardet #字符集检测
import urllib.request
 
# 网址
url = "http://www.baidu.com/"url


def automatic_detect(url): 
    content=urllib.request.urlopen(url).read() 
    result=chardet.detect(content)
    encoding=result['encoding'] 
    return encoding code

print(url) 
print(automatic_detect(url))utf-8

# 请求
request = urllib.request.Request(url)
# 爬取结果
response = urllib.request.urlopen(request)
data = response.read()
# 设置解码方式
data = data.decode('utf-8')get

# 打印爬取网页的各种信息
# 打印结果
print(data)
print(type(response))
print(response.geturl())
print(response.info())
print(response.getcode())import


 

须要安装chardetcoding

相关文章
相关标签/搜索