python之http.client使用https协议

概述

访问百度等一些网站,这些网站只支持https协议,在对这类网站进行访问抓取时,要使用http.client.HTTPSConnection 类,其他代码基本不变

例子

import http.client

domain='www.oschina.net'
url='/'
try:
    conn=http.client.HTTPSConnection(domain)
    conn.request("GET",url)
    resp = conn.getresponse()
    print(resp.status, resp.reason,resp.version)
    print(resp.headers)
    if resp.status==200:
        data = resp.read()
        contenttype=resp.getheader('Content-Type')
        if contenttype.find('charset=')>=0:
            charset=contenttype.split('charset=')[1]
        else:
            charset='utf-8'
        print( data.decode(charset))
except :
    conn.close()
    raise

原文出处:/show_1EF2ba6tuGqV.html