美文网首页
Python之Requests模块

Python之Requests模块

作者: Twins_zuoyou | 来源:发表于2018-11-26 14:45 被阅读0次

Requests 模块说明:
支持HTTP连接保持和连接池,支持cookie保持会话,支持文件上传,支持自动确定响应内容编码,支持国家化的URL和POST数据自动编码。

requests模块安装

pip install requests

Requests模块简单入门:

import requests
# 尝试获取某个网页,如:百度
r = requests.get('https://www.baidu.com/')  # 访问成功,返回200

# 发送HTTP POST请求
r =  requests.post('http://httpbin.org/post', data = {'key':'value'})

# 对于其他的http请求的操作

r = requests.put('http://httpbin.org/put', data = {'key':'value'})
r = requests.delete('http://httpbin.org/delete')
r = requests.head('http://httpbin.org/get')
r = requests.options('http://httpbin.org/get')

带参数的请求实例:
发送带参数的get请求,get请求是以关键字params传递参数的
发送带参数的post请求,post请求是以关键字data传递参数的

import requests
requests.get('http://www.dict.baidu.com/s', params={'wd': 'python'})    #GET参数实例
requests.post('http://www.itwhy.org/wp-comments-post.php', data={'comment': '测试POST'})    #POST参数实例

Post发送Json实例:

import requests
import json
 
r = requests.post('https://api.github.com/some/endpoint', data=json.dumps({'some': 'data'}))
print(r.json())

Post一个文件:

url='https://www.baidu.com'
files={'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)

# 可以在post文件时指定文件名等额外的信息:
url = 'http://pythontab.com/postTest'
files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
r = requests.post(url, files=files) 

传递url参数
如果是手工构建的URL,数据会以键值对的模式存储在URL中,跟在一个问号的后面。如,login的api/user/login?username='tester'&passwd='aA123456'。 Requests允许使用params关键字参数,以一个字符串字典来提供这些参数

payload = {'username':'tester','passwd':'aA123456'}
r = requests.post('http://hostNmae/api/user/login',params=payload)
# 返回 200
print(r.url)# 通过打印输出该 URL,URL 已被正确编码

响应内容: 读取服务器响应内容
Requests会自动解码来自服务器的内容。大多数的Unicode字符集都能被无缝解码。

r = requests.get('https://www.baidu.com/')r
r.text # content of the response, in unicode
r.content # 以字节的方式访问请求响应体,
r.content.decode() # 加上decode方法

订制请求头
如果想为请求添加HTTP 头部,只要简单传递一个dict给header就可以了。
例如,指定content-type:

url = 'http://m.ctrip.com'
headers = {'User-Agent' : 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19'}
r = requests.post(url, headers=headers)
print(r.request.headers)

注意: 所有的 header 值必须是 string、bytestring 或者 unicode。尽管传递 unicode header 也是允许的,但不建议这样做。

更加复杂的POST请求

url = 'http://m.ctrip.com'
payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload)) #如果传递的payload是string而不是dict,需要先调用dumps方法格式化一下

返回状态码

r = requests.get('https://www.baidu.com/') 
r.status_code

响应头

r = requests.get('https://www.baidu.com/')
print(r.headers)
print(r.headers['Content-Type'])
print(r.headers.get('content-type'))

设置访问代理

#设置访问代理
proxies = {
           "http": "http://10.10.10.10:8888",
           "https": "http://10.10.10.100:4444",
          }
r = requests.get('http://m.ctrip.com', proxies=proxies)

下载页面

r=requests.get("http://www.pythontab.com")
with open("haha.html","wb") as html:
    html.write(r.content)
html.close()

Requests整合案例1:

import requests
import nnlog
import os
from conf.setting import LOG_PATH
class MyRequest:
    log_file_name  = os.path.join(LOG_PATH,'MyRequest.log')#日子文件名
    time_out = 10 #请求超时时间
    def __init__(self,url,data=None,headers=None,file=None):
        self.url = url
        self.data = data
        self.headers = headers
        self.file = file
    def post(self):
        try:
            req = requests.post(self.url,data=self.data,headers=self.headers,
                                files=self.file,timeout=self.time_out)
        except Exception as e:
            res = {"status":0,"data":e.args}  #0代表请求失败
        else:
            try:
               res = {"status":1,"data":req.json()} #1代表返回的json
            except Exception as e:
                res = {"staus":2,"data":req.text} #2代表返回不是json
        log_str = 'url: %s 请求方式:post  data:%s ,返回数据:%s'%(self.url,self.data,res)
        self.write_log(log_str)
        return res

    def get(self):
        try:
            req = requests.get(self.url,params=self.data,headers=self.headers,timeout=self.time_out)
        except Exception as e:
            res = {"status":0,"data":e.args}  #0代表请求失败
        else:
            try:
               res = {"status":1,"data":req.json()} #1代表返回的json

            except Exception as e:
                res = {"staus":2,"data":req.text} #2代表返回不是json
        log_str = 'url: %s get请求 data:%s ,返回数据:%s'%(self.url,self.data,res)
        self.write_log(log_str)
        return res

    @classmethod
    def write_log(cls,content):
        log = nnlog.Logger(cls.log_file_name)
        log.debug(content)

参考文档:http://docs.python-requests.org/zh_CN/latest/user/advanced.html#advanced

相关文章

网友评论

      本文标题:Python之Requests模块

      本文链接:https://www.haomeiwen.com/subject/blwpqqtx.html