python模块系列之-urllib2

来源:互联网 发布:刘亦菲 陈金飞 知乎 编辑:程序博客网 时间:2024/05/21 09:13

前提:运行环境:python2.7.9,网上有好些资料因为 python版本的不同命令有些不同。
我没有用python 3.x,据网友提供的信息说:
python 3.x中urllib库和urilib2库合并成了urllib库。。
其中urllib2.urlopen()变成了urllib.request.urlopen()
urllib2.Request()变成了urllib.request.Request()

以下是我们最常见、最简单的两种写法:

import urllib2 response = urllib2.urlopen('http://python.org/') html = response.read()

或者

import urllib2 request=urlib2.Request("http://python.org/")response = urllib2.urlopen(request) html = response.read()

urllib2.urlopen(url[, data][, timeout])
- url表示目标网页地址,可以是字符串,也可以是请求对象Request
- data表示post方式提交给目标服务器的参数,如果该参数为空,表-示以get方式提示,如果该参数不为空,表示以post方式提交。
- timeout表示超时时间

urllib2.Request(url[, data][, headers][, origin_req_host][, unverifiable])
- url表示目标网页地址
- data表示post方式提交给目标服务器的参数,如果该参数为空,表-示以get方式提示,如果该参数不为空,表示以post方式提交。
- headers表示用户标识,是一个字典类型的数据,有些不允许脚本的抓取,所以需要修改下,像火狐浏览器的代理就是类似:Mozilla/5.0 (X11; U; Linux i686)Gecko/20071127 Firefox/2.0.0.11 浏览器的标准UA格式为:浏览器标识 (操作系统标识; 加密等级标识; 浏览器语言) 渲染引擎标识 版本信息 ,headers默认是python-urllib/2.6
- origin_req_host表示请求方的主机域名或者ip地址

通过对比我们发现有重合的功能,所以如果只是简单的网页请求,只用urllib2.urlopen就可以。但是,如果要完成一些复杂些的功能,就需要借助urllib2.Request。比如:

要加入 Header,需要使用 Request 对象, 还需要使用add_header:

import urllib2 request = urllib2.Request(url)request.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; rv:53.0) Gecko/20100101 Firefox/53.0')response = urllib2.urlopen(request)

POST

一般的HTML表单,data需要编码成标准形式。然后做为data参数传到Request对象。编码工作使用urllib的函数而非urllib2。

import urllib import urllib2 url = 'http://www.pythontab.com' values = {'name' : 'Michael Foord',           'location' : 'pythontab',           'language' : 'Python' } data = urllib.urlencode(values) req = urllib2.Request(url, data) response = urllib2.urlopen(req) the_page = response.read()

urlopen返回的应答对象response常用方法:
getcode() : HTTP 的返回码
geturl():返回页面的URL值,主要是用来检测页面是否发生了跳转。(urllib2 默认情况下会针对 3xx HTTP 返回码自动进行 Redirect 动作,无需人工配置。要检测是否发生了 Redirect 动作,只要检查一下 Response 的 URL 和 Request 的 URL 是否一致就可以了。)
info():这个返回对象的字典对象,该字典描述了获取的页面情况。通常是服务器发送的特定头headers。
read():返回网页内容

引用

http://blog.csdn.net/youfuchen/article/details/19492821`
http://www.pythontab.com/html/2014/pythonhexinbiancheng_1128/928.html
http://www.pythontab.com/html/2014/pythonhexinbiancheng_1128/928.html