网页下载器
慕课网《python开发简单爬虫》之下载网页源码的三种方式
#coding:utf-8 import urllib.request from http.cookiejar import CookieJar url='http://www.baidu.com' PRint('第一种方法') res1=urllib.request.urlopen(url) print(res1.getcode()) #打印状态码,200表示成功 print(len(res1.read())) print('第二种方法') #添加header,伪装成Mozilla浏览器 request=urllib.request.Request(url,headers={'user-agent':'Mozilla/5.0'}) res2=urllib.request.urlopen(request) print(res2.getcode()) print(len(res2.read())) print('第三种方法') #使用cookies模拟登录 cj=CookieJar() #创建cookies容器 opener=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) urllib.request.install_opener(opener) #安装opener 使urllib具有处理cookies的能力 res3=urllib.request.urlopen(url) print(res3.getcode()) print(res3.read()) #打印网页源代码---注意网页源码编码格式是否需要转码 print(cj) #打印cookies内容