requests库

一、安装

pip install requests

二、初试

import requests
#使用get方法访问百度
r = requests.get('http://www.baidu.com')
#状态码
r.status_code    
Out[4]: 200
#设置返回内容的编码格式为utf-8
r.encoding='utf-8'  
#显示返回对象的内容
r.text

三、requests库的常用7个方法

方法说明备注
requests.request()构造一个请求,支撑以下各方法 的基础方法
requests.get()获取html页面的主要方法,对应于HTTP的GETGET:请求获取URL位置的资源
requests.head()获取HTML网页头信息的方法,对应于HTTP的HEADHEAD:请求获取URL位置资源的响应消息报告,即获得该资源的头部信息
requests.post()向网页提交POST请求的方法,对应HTTP的POSTPOST:请求向URL位置的资源后附加新的数据
requests.put()向网页提交PUT请求的方法,对应HTTP的PUTPUT:请求向URL位置存储一个资源,覆盖源URL位置的资源
requests.patch()向网页提交局部修改请求,对应HTTP的PATCH请求局部更新URL位置的资源,即改变该处资源的部分内容
requests.delete()向网页提交删除请求,对应HTTP的DELETE请求删除URL位置存储的资源

注意:put和patch方法的区别
假设URL位置上有一组数据userinfo,包括userid、username等20个字段
需求:用户修改了username,其他不变
采用patch,仅向URL提交username的局部更新请求。
采用put,必须将所有20个字段一并提交到URL,未提交字段被删除
patch的最主要用处:节省网络带宽

3.1 requests.get方法

requests.get(url, params=None, **kwargs)
- url:拟获取页面的URL链接;格式 ---url='http://www.baidu.com'
- params:url中的额外参数,字典或字节流格式,可选
- **kwargs:12个访问控制的参数

url格式 http://host[:port][path]
host:合法的Internet主句域名或IP地址
port:端口后,缺省端口为80
path:请求资源的路径

3.1.1 Response对象的属性

Response对象的属性说明备注
r.status_codeHTTP请求的返回状态,200表示连接成功,404表示失败
r.textHTTP响应内容的字符串形式,即url对应的页面内容
r.encoding从HTTP header 中猜测的向相应内容的编码格式
r.apparent_encoding从内容中分析的响应内容编码格式
r.contentHTTP响应内容的二进制形式

3.1.2 异常

Requests库的异常说明备注
r.raise_for_status如果不是200,产生异常requests.HTTPError
requests.ConnectionError网络连接错误,如DNS查询失败、防火墙拒绝连接
requests.HTTPErrorHTTP错误异常
requests.URLRequiredURL缺失异常
requests.TooManyRedirects超过最大重定向次数,产生重定向异常
requests.ConnetcTimeout连接远程服务器超时异常仅指连接到服务器的时间
requests.Timeout请求URL超时,产生超时异常客户端产生连接到收到返回内容的时间

3.1.3常用框架流程

Created with Raphaël 2.1.0 requests.get() r.status_code 是否是200 正常结束 r.text、r.encoding 、r.apparent_encoding、 r.content 异常(404或其他) yes no

3.1.4常用框架

# -*- coding: utf-8 -*-
"""
Created on Thu May 18 20:33:42 2017

@author: suning 1107914055@qq.com
"""

import requests

def getHTMLText(url):
    try:        
        r = requests.get(url)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        #return r.text
        return r.headers        
    except:
        return '产生异常'      

if __name__ == "__main__":
    url = "http://www.baidu.com"
    print(getHTMLText(url))

3.2 requests.head方法

r = requests.head("http://httpbin.org/get")

print(r.headers)
{'Connection': 'keep-alive', 'Server': 'meinheld/0.6.1', 'Date': 'Fri, 19 May 2017 05:38:50 GMT', 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', 'X-Powered-By': 'Flask', 'X-Processed-Time': '0.000622987747192', 'Content-Length': '267', 'Via': '1.1 vegur'}

3.3requests.post方法

post 一个字典

payload = {'key1':'value1','key2':'value2'}
r = requests.post('http://httpbin.org/post',data = payload)
print(r.text)
{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "key1": "value1", 
    "key2": "value2"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Content-Length": "23", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.12.4"
  }, 
  "json": null, 
  "origin": "223.167.127.235", 
  "url": "http://httpbin.org/post"
}

post 一个字符串

n [22]: r = requests.post('http://httpbin.org/post',data = 'abxcc')

print(r.text)
{
  "args": {}, 
  "data": "abxcc", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Content-Length": "5", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.12.4"
  }, 
  "json": null, 
  "origin": "223.167.127.235", 
  "url": "http://httpbin.org/post"
}

put一个字典(覆盖原有数据)

r = requests.put('http://httpbin.org/put',data = payload)

print(r.text)
{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "key1": "value1", 
    "key2": "value2"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Content-Length": "23", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.12.4"
  }, 
  "json": null, 
  "origin": "223.167.127.235", 
  "url": "http://httpbin.org/put"
}

主要方法

requests.request(method,url,**kwargs)
method:请求方式,对应get/put/post等7种
url:拟获取页面的URL链接
**kwargs:控制访问的参数,共13
TablesAreCool

访问控制参数1:
params:字典或字节序列,作为参数增加到url中

>>> kv = {'key1':'value1','key2':'value2'}
>>> r = requests.request('GET','http://python123.io/ws',params=kv)
>>> print r.url
'http://python123.io/ws?key1=value1&key2=value2'

访问控制参数2:
data:字典、字节序列或文件对象,作为Request的内容

#data是字典
>>>  payload = {'key1':'value1','key2':'value2'}
>>>  r = requests.post('http://httpbin.org/post',data = payload)
>>>  print(r.url)
http://httpbin.org/post
>>>  print(r.text)
{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "key1": "value1", 
    "key2": "value2"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Content-Length": "23", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.12.4"
  }, 
  "json": null, 
  "origin": "223.167.127.235", 
  "url": "http://httpbin.org/post"
}
#data是字符串
>>>   r = requests.post('http://httpbin.org/post',data = 'text')

>>>   print(r.url)
'http://httpbin.org/post'

>>>   print(r.text)
{
  "args": {}, 
  "data": "text", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Content-Length": "4", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.12.4"
  }, 
  "json": null, 
  "origin": "223.167.127.235", 
  "url": "http://httpbin.org/post"
}
#data是文件对象
>>>   file = open('D:/file1.txt',mode='r')
>>>   r = requests.post('http://httpbin.org/post',data = file)
>>>   r.url
'http://httpbin.org/post'
>>>   print(r.text)
{
  "args": {}, 
  "data": "iiiiiiiiiiii:", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Content-Length": "13", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.12.4"
  }, 
  "json": null, 
  "origin": "223.167.127.235", 
  "url": "http://httpbin.org/post"
}

访问控制参数3:
json:JSON格式的数据,作为Request的内容

>>>   kv = {'key1': 'value1', 'key2': 'value2'}

>>>   r = requests.request('POST','http://python123.io/ws',json=kv)

>>>   print(r.url)
'http://python123.io/ws'

>>>   print(r.text)
Not Found

访问控制参数4:
headers:字典,HTTP定制头

hd = {'user-agent','Chrome/10'}
r = requests.request('POST','http://python123.io/ws',headers=hd)

访问控制参数5:
cookies:字典或CookerJar,request中的cookie
访问控制参数6:
auth:元组,支持HTTP认证功能
访问控制参数7:
files:字典类型,传输文件

fs = {'file':open('D:/data.xls','rb')}
r = requests.request('POST','http://python123.io/ws',files=fs)

访问控制参数8:
timeout:设定超时时间,单位为秒

r = requests.request('GET','http://www.baidu.com',timeout=10)

访问控制参数9:
proxiex:字典类型,设定访问代理服务器,可以增加登录认证

>>> pxs = {'http':'http://user:pass@10.10.10.1:1234' 'https':'https://10.10.10.1:4321'}
>>> r =requests.request('GET','http://www.baiud.com',proxies=pxs)

访问控制参数10:
allow_redirects:True/False,默认为True,默认为True,重定向开关
访问控制参数11:
stream:True/False,默认为True,获取内容立即下载开关
访问控制参数12:
verify:True/False,默认为True,认证SSL证书开关
访问控制参数13:
cert:本地SSL证书路径

应用

百度的关键词接口:
https:www.baidu.com/s?wd=keyword

kv = {'wd':'keyword'}
r = requests.get('http://www.baidu.com/s',params=kv)

360的关键词接口
http://www.so.com/s?q=keyword

kv = {'q':'keyword'}
r = requests.get('http://www.so.com/s',params=kv)

图片爬取

#!/usr/local/python-2.7.13/bin/virtualenv python
# -*- coding: utf-8 -*-
"""
Created on Thu May 18 20:33:42 2017

@author: suning 1107914055@qq.com
"""

import requests
import os
url = "http://www.qzone.la/DownFile/354878/1448965"
root = "/tmp/pic/"
path = root + url.split('/')[-1] + ".jpg"

try:
    if not os.path.exists(root):
        os.mkdir(root)

    if not os.path.exists(path):
        r = requests.get(url)
        with open(path,'wb') as f:
            f.write(r.content)
            f.close()
            print('文件以保存')

    else:
        print('文件已存在')
except:
    print('爬取失败')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值