慕课网《python开发简单爬虫》之下载网页源码的三种方式
#coding:utf-8import urllib.requestfrom http.cookiejar import CookieJarurl='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内容新闻热点
疑难解答