您的位置:首页 > 其它

三种方法实现网页下载-(慕课网学习笔记)

2016-05-12 12:07 549 查看

网页下载器

网页下载器是将URL对应的网页下载到本地的工具

Python网页下载器:

urllib2 : Python官方基础模块

requests : 第三方插件,功能更强大

三种下载网页的方法

最简洁最传统:

urllib2.urlopen(url)


需向服务器提供data,http header等信息:

request = urllib2.Request(url)

request.add_header("user-agent","Mozilla/5.0")

添加特殊情景的处理器

eg.

HTTPCookieProcessor 用户登录才能访问

ProxyHandler 需要代理才能访问

HTTPSHandler 协议用HTTPS加密访问的网站

HTTPRedirectHandle 相互自动跳转

以cookie为例:

cookie = cookielib.CookieJar()

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))

urllib2.install_opener(opener)

*****************源码

import urllib2,cookielib

url = "http://www.baidu.com"
print "第一种方法"
# 直接请求
response1 = urllib2.urlopen(url)
# 获取状态码,如果是200表示获取成功
print response1.getcode()
# 读取内容
print len(response1.read())

print "第二种方法"
# 创建request对象
request = urllib2.Request(url)
# 模拟浏览器访问
request.add_header("user-agent","Mozilla/5.0")

response2 = urllib2.urlopen(url)
print response2.getcode()
print len(response2.read())

print "第三种方法"
# 创建cookie容器
cookie = cookielib.CookieJar()
# 创建一个opener
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
# 给urllib2安装opener
urllib2.install_opener(opener)

response3 = urllib2.urlopen(url)
print response3.getcode()
print response3.read()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: