目录
Python2.x中
Urllib和Urllib2
urllib 和 urllib2 是 python2.x 自带的模块,提供了一系列用于操作URL的功能。
urllib 和 urllib2 都是接受URL请求的相关模块,但是urllib2可以接受一个Request类的实例来设置URL请求的headers,urllib 仅可以接受URL。这意味着,urllib不可以伪装你的User Agent 字符串等。
但是urllib提供 urlencode 方法用来GET查询字符串的产生,而 urllib2 没有,所以 urllib 经常和 urllib2 一起使用。
常用方法和类:
urllib2.urlopen(url [, data] [, timeout])
urlopen方法是urllib2模块最常用也最简单的方法,它打开URL网址,url参数可以是一个字符串 url 或者是一个Request对象。
- 对于可选参数 data,表示以post方式提交到url的数据。不填则为get请求
- 对于可选的参数 timeout,阻塞操作以秒为单位,如尝试连接(如果没有指定,将使用设置的全局默认timeout值)。实际上这仅适用于HTTP,HTTPS和FTP连接。
import urllib2
response = urllib2.urlopen('http://python.org/')
html = response.read()
urllib2.urlopen( urllib2.Request )
urlopen方法也可通过建立了一个Request对象来明确指明想要获取的url。调用urlopen函数对请求的url返回一个response对象。这个response类似于一个file对象,所以用.read()函数可以操作这个response对象
import urllib2
req = urllib2.Request('http://python.org/')
response = urllib2.urlopen(req)
the_page = response.read()
这里用到了urllib2.Request 类,对于上例,我们只通过了URL实例化了Request类的对象,其实Request类还有其他的参数 。
class urllib2.Request(url [, data] [, headers] [, origin_req_host] [, unverifiable])
- 对于可选参数data,data 是一个字符串,指定额外的数据发送到服务器,如果没有data需要发送可以不写。目前使用data的HTTP请求是唯一的。当请求含有data参数时,HTTP的请求为POST,而不是GET。数据应该是缓存在一个标准的application/x-www-form-urlencoded格式中。urllib.urlencode()函数用映射或2元组,返回一个这种格式的字符串。通俗的说就是如果想向一个URL发送数据(通常这些数据是代表一些CGI脚本或者其他的web应用)。对于HTTP来说这动作叫Post。例如在网上填的form(表单)时,浏览器会POST表单的内容,这些数据需要被以标准的格式编码(encode),然后作为一个数据参数传送给Request对象。Encoding是在urlib模块中完成的,而不是在urlib2中完成的。所以得urllib和urllib2一起结合使用
import urllib
import urllib2
requrl = 'http://www.someserver.com/cgi-bin/register.cgi'
values = {'name': 'Tom',
'sex' : 'Man',
'id' : '10' }
data = urllib.urlencode(values)
req = urllib2.Request(url=requrl, data=data)
response = urllib2.urlopen(req)
the_page = response.read()
- 可选参数headers是字典类型,头字典可以作为参数在request时直接传入,也可以把每个键和值作为参数调用add_header()方法来添加。作为辨别浏览器身份的User-Agent。header是经常被用来恶搞和伪装的,因为一些HTTP服务只允许某些请求来自常见的浏览器而不是脚本,或是针对不同的浏览器返回不同的版本。例如,Mozilla Firefox浏览器被识别为“Mozilla/5.0 (X11; U; Linux i686)Gecko/20071127Firefox/2.0.0.11”。默认情况下,urllib2把自己识别为Python-urllib/x.y (这里的xy是python发行版的主要或次要的版本号,如在Python2.6中,urllib2的默认用户代理字符串是“Python-urllib/2.6)。下面的例子在请求时加了一个headers,模仿IE浏览器提交请求。
import urllib
import urllib2
requrl = 'http://www.baidu.com/login.php'
values = {'name': 'Tom',
'sex' : 'Man',
'id' : '10' }
data = urllib.urlencode(values)
header = { 'Host': '192.168.153.130',
'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
'Referer' : 'http://www.python.org/',
'Accept' : '*/*' }
req = urllib2.Request(url=requrl, data=data,headers=header)
response = urllib2.urlopen(req)
the_page = response.read()
##还可以使用add_header方法添加
import urllib2
requrl = 'http://www.baidu.com/login.php'
values = {'name': 'Tom',
'sex' : 'Man',
'id' : '10' }
data = urllib.urlencode(values)
req = urllib2.Request(url=requrl,data=data,headers)
req.add_header('Referer', 'http://www.python.org/')
response = urllib2.urlopen(req)
the_page = response.read()
- 可选参数origin_req_host是RFC2965定义的源交互的request-host。默认的取值是cookielib.request_host(self)。这是由用户发起的原始请求的主机名或IP地址。例如,如果请求的是一个HTML文档中的图像,这应该是包含该图像的页面请求的request-host。
- 可选参数unverifiable代表请求是否是无法验证的,它也是由RFC2965定义的。默认值为false。一个无法验证的请求是,其用户的URL没有足够的权限来被接受。例如,如果请求的是在HTML文档中的图像,但是用户没有自动抓取图像的权限,unverifiable的值就应该是true。
Python3.x中
urllib
在python3.x中,把 http 相关的所有包打包成了2个包:http 和 urllib
http 会处理所有客户端--服务器http请求的具体细节,其中:
- client 会处理客户端的部分
- server 会协助你编写Python web服务器程序
- cookies 和cookiejar会处理cookie,cookie可以在请求中存储数据
urllib 是基于 http 的高层库,它有以下三个主要功能:
- reques t处理客户端的请求
- response 处理服务端的响应
- parse 会解析url
常见的类和方法
request.urlopen(url [, data] [, timeout])
参数选项和python2.x中的 urllib.urlopen 一样
from urllib import request
response = request.urlopen('http://python.org/')
html = response.read()
request.urlopen( request.Request )
参数选项和python2.x中的 urllib.urlopen 一样
from urllib import request
req = request.Request('http://python.org/')
response = request.urlopen(req)
the_page = response.read()
自定义 headers 和 data
from urllib import parse
from urllib import request
url = 'http://www.someserver.com/cgi-bin/register.cgi'
headers = { 'Host': '192.168.153.130',
'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
'Referer' : 'http://www.python.org/',
'Accept' : '*/*' }
values = {'name': 'Tom',
'sex' : 'Man',
'id' : '10' }
data = urllib.parse.urlencode(values)
req = urllib.request.Request(url, data)
response = urllib.request.urlopen(req)
the_page = response.read()
print(the_page.decode("utf8"))
requests
而requests库则是非常优秀的第三方库,它使用 Apache2 Licensed 许可证的 HTTP 库,用 Python 编写,真正的为人类着想。Requests 使用的是 urllib3(python3.x中的urllib),因此继承了它的所有特性。Requests 支持 HTTP 连接保持和连接池,支持使用 cookie 保持会话,支持文件上传,支持自动确定响应内容的编码,支持国际化的 URL 和 POST 数据自动编码。现代、国际化、人性化
requests模块中可以有很多种请求网页的方式
- requests.get('http://www.baidu.com')
- requests.post('http://www.baidu.com')
- requests.put('http://www.baidu.com')
- requests.delete('http://www.baidu.com')
- requests.head('http://www.baidu.com')
- requests.options(http://www.baidu.com')
import requests
headers = { 'Host': '192.168.153.130',
'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
'Referer' : 'http://www.python.org/',
'Accept' : '*/*' }
values = {'name': 'Tom',
'sex' : 'Man',
'id' : '10' }
proxie={"http":"http://127.0.0.1:8080"} #设置代理
response=requests.get('http://www.baidu.com',params=values,headers=headers,timeout=0.1,proxies=proxie)
print( response.request.headers ) #查看我们的请求头
print( response.url ) #查看我们提交的url
print( responce.status ) #查看响应码
print( repsonse.headers) #查看响应头
print( responce.headers['Content-Type']) #查看响应头的具体部分
response.encoding='utf-8' #修改网页的编码
print( responnse.content ) #以字节的方式去显示响应的内容
print( response.text ) #以文本的方式去显示响应的内容