同步请求库requests用来做测试和简单爬虫其实非常好用的,今天来讲一讲,毕竟不熟悉就用,吃了很大亏啊,文档一定要好好看

http://docs.python-requests.org/zh_CN/latest/user/quickstart.html

一、最简单常用的用法

GET请求

response = requests.get('http://httpbin.org/get')
print(response.text) # 输出
{
"args": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.21.0"
},
"origin": "xx.xx.xx.xx",
"url": "http://httpbin.org/get"
}

POST请求

form = {'name': 'happy_codes'}
response = requests.post('http://httpbin.org/post', data=form)
print(response.text) # form表单数据
{
"args": {},
"data": "",
"files": {},
"form": {
"name": "happy_codes"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Content-Length": "",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.21.0"
},
"json": null,
"origin": "xx.xx.xx.xx",
"url": "http://httpbin.org/post"
}

二、加UA,加cookies,加代理

cookies除了使用dict之外,还可以使用cookiejar类,还可以直接给字符串

proxies={'http:': 'http://127.0.0.1', 'https': 'http:127.0.0.1'}

意思是http协议和https协议使用怎样的代理,没配置正确,就不会用代理,切记。

headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"} cookies = {"STM": "", 'haha': ''} response = requests.get('http://httpbin.org/get', headers=headers, cookies=cookies,
proxies={'http': 'http://125.123.122.10:42207', 'https': 'http://125.123.122.10:42207'}) print(response.text) # 输出
{
"args": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Cookie": "STM=1545720205; haha=123",
"Host": "httpbin.org",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
},
"origin": "125.123.122.10:42207",
"url": "http://httpbin.org/get"
}

其实可以加的,都写在注释里面了,GET,POST都一样:

def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`. :param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary, list of tuples or bytes to send
in the body of the :class:`Request`.
:param data: (optional) Dictionary, list of tuples, bytes, or file-like
object to send in the body of the :class:`Request`.
:param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.
:param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
:param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
:param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
to add for the file.
:param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
:param timeout: (optional) How many seconds to wait for the server to send data
before giving up, as a float, or a :ref:`(connect timeout, read
timeout) <timeouts>` tuple.
:type timeout: float or tuple
:param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
:param verify: (optional) Either a boolean, in which case it controls whether we verify
the server's TLS certificate, or a string, in which case it must be a path
to a CA bundle to use. Defaults to ``True``.
:param stream: (optional) if ``False``, the response content will be immediately downloaded.
:param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
:return: :class:`Response <Response>` object
:rtype: requests.Response Usage:: >>> import requests
>>> req = requests.request('GET', 'https://httpbin.org/get')
<Response [200]>
"""

三、session类的使用

Session类的作用是用来维持一个会话,可以让多个请求共用cookie和headers和proxies

headers->dict类型,可以通过 session.headers.update(headers) 更新

cookies->cookie Jar类, 可使用 session.cookies.set(key, value) 更新

proxies->dict类型, 可以通过直接赋值 session.proxies = proxies 更新

通过 session.get() 发起请求

headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"} proxy = '59.61.38.48:34719'

# requests.Session类
session = requests.Session() session.headers.update(headers)
session.cookies.set('STM', '')
session.cookies.set('S', '') proxies = {
'http': 'http://%s' % proxy,
'https': 'http://%s' % proxy
}
session.proxies = proxies print(session.get('http://httpbin.org/get').text) # 输出

{
"args": {},
"headers": {
  "Accept": "*/*",
  "Accept-Encoding": "gzip, deflate",
  "Cache-Control": "max-age=259200",
  "Connection": "close",
  "Cookie": "S=123123; STM=1231214",
  "Host": "httpbin.org",
  "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
},
"origin": "59.61.38.48",
"url": "http://httpbin.org/get"
}

python3-requests库的使用的更多相关文章

  1. python3+requests库框架设计01-自动化测试框架需要什么?

    什么是自动化测试框架 关于自动化测试框架的定义有很多,在我大致理解下就是把能实现不同功能的软件组合在一起,实现特定的目的,这就是一个简单的自动化测试框架. 接口自动化测试框架核心无非是选择 一个用来编 ...

  2. Python常见问题 - python3 requests库提示警告InsecureRequestWarning的问题

    当使用 requests 库发送请求时报了以下警告 D:\python3.6\lib\site-packages\urllib3\connectionpool.py:847: InsecureRequ ...

  3. python3 requests库学习笔记(MOOC网)

    奏:HTTP协议对资源的操作 方法说明:GET 请求获取URL位置的资源HEAD 请求获取URL位置资源的响应消息报告,即获得该资源的头部信息POST 请求向URL位置的资源后附加新的数据PUT 请求 ...

  4. python3+requests库框架设计08-发送邮件

    使用python3的email模块和smtplib模块可以实现发送邮件的动能.email模块用来生成email,smtplib模块用来发送邮件,接下来看如何在生成测试报告之后,并将报告放在邮件附件中并 ...

  5. python3+requests库框架设计04-配置文件

    python3配置文件的增删改查等操作可以使用内置的ConfigParser模块,可以自行百度学习,也可以看Python3学习笔记27-ConfigParser模块 配置文件一般存放着环境信息,比如u ...

  6. python3+requests库框架设计03-请求重新封装

    在完成了日志类封装之后,那我们就要对测试基类进行实现,在其中对一些请求再次封装,在项目下新建一个Common文件夹,在文件夹下新建Base_test.py文件,项目结构如下. 具体怎么封装还是要看被测 ...

  7. python3+requests库框架设计02-封装日志类

    首先我们先来实现日志的功能,日志可以使用python3自带logging模块,不会的可以百度一下相关文章,也可以看我另外一篇文章Python3学习笔记24-logging模块 在封装日志类前,我们需要 ...

  8. Python3 requests 库

    requests 安装 使用 requests 发送 GET 请求 使用 requests 发送 POST 请求 使用 requests 维持会话 使用 requests 访问 HTTPS 使用 re ...

  9. python3+requests库框架设计07-生成测试报告

    使用HTMLTestRunner可以生成测试报告.HTMLTestRunner是unittest模块下的一个拓展,原生的生成报告样式比较丑,GitHub上有大佬优化过后的版本:GitHub地址.下载之 ...

  10. python3+requests库框架设计06-测试脚本

    在项目下新建TestCase文件夹,然后新建.py文件在文件中写关于接口具体的测试脚本,一般我喜欢按照模块来分,一个模块一个.py文件,建议以test开头命名文件 把配置文件改成这样 url:http ...

随机推荐

  1. 缓存server设计与实现(五)

    上次讲到lru与缓存重建,这次主要讲一下关于过期处理的一些主要问题. 在讨论这个问题之前,有个相关的问题须要大家有所了解. 就是对于一个缓存如期仅仅来说,什么东西应该缓存,什么不应该缓存.这是一个比較 ...

  2. CGROUP相关知识

    安装 CentOS 6 yum install libcgroup CentOS 7 yum install libcgroup-tools 使用 默认情况下有几个控制器可以进行限制,分别是 cpus ...

  3. ThreadPoolExecutor线程池解析与BlockingQueue的三种实现

    目的 主要介绍ThreadPoolExecutor的用法,和较浅显的认识,场景的使用方案等等,比较忙碌,如果有错误还请大家指出 ThreadPoolExecutor介绍 ThreadPoolExecu ...

  4. SAP ECC6安装系列五:安装后 License 的处理

    原作者博客 http://www.cnblogs.com/Michael_z/ ======================================== 我发现我确实比较懒,先和各位说声抱歉了 ...

  5. nyoj16矩形嵌套(第一道dp关于dag的题目)

    http://acm.nyist.net/JudgeOnline/problem.php?pid=16 题意:有n个矩形,每个矩形可以用a,b来描述,表示长和宽.矩形X(a,b)可以嵌套在矩形Y(c, ...

  6. (转载) STL中map用法详解

    Map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据处理能力,由于这个特性,它完成有可能在我们处理一对一数据的时候 ...

  7. spring 注解@Resource @Autowired区别

    1.@Autowired寻找类的时候默认是ByType,也就是通过类的类型来寻找类.不过,也可以通过借助@Qualifier("name")来指定寻找的类名 @Autowired ...

  8. NSURLErrorDomain Code=-999(转)

    原文:http://www.henishuo.com/nsurlerrordomain-code-999/ 前言 今天有一个线上bug,是分配给提供H5的团队的,但是后台查不出来原因.于是让前端iOS ...

  9. /proc/meminfo分析

    参考: 1. linux/Documentation/filesystems/proc.txt 2. Linux 中 /proc/meminfo 的含义 3. redhat deployment gu ...

  10. Goroutine并发调度模型深度解析之手撸一个协程池

    golanggoroutine协程池Groutine Pool高并发 并发(并行),一直以来都是一个编程语言里的核心主题之一,也是被开发者关注最多的话题:Go语言作为一个出道以来就自带 『高并发』光环 ...