requests模块

requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库,requests会比urllib更加方便,可以节约我们大量的工作。

requests是python实现的最简单易用的HTTP库,建议爬虫使用requests库。默认安装好python之后,是没有安装requests模块的,需要单独通过pip安装

requests请求

requests模块支持的请求

import requests
requests.get("http://httpbin.org/get")
requests.post("http://httpbin.org/post")
requests.put("http://httpbin.org/put")
requests.delete("http://httpbin.org/delete")
requests.head("http://httpbin.org/get")
requests.options("http://httpbin.org/get") 

GET请求

1 基本请求

res = requests.get('https://www.jd.com/')

with open("jd.html", 'wb') as f:
f.write(res.content)

2 含参数请求

params参数指url '?'后的键值对

res = requests.get('https://list.tmall.com/search_product.html')
res = requests.get('https://list.tmall.com/search_product.htm', params={"q": "手机"}) with open('tao_bao.html', 'wb') as f:
f.write(res.content)

3 含请求头请求

res = requests.get("https://dig.chouti.com/", headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36'
}) with open('chouti.html', 'wb') as f:
f.write(res.content)

4 含cookies请求

import uuid

res = requests.get("http://httpbin.org/cookies", cookies={'sbid': str(uuid.uuid4()), 'a': ''})
print(res.text)

5 session对象

session = requests.session()
session.post('/login/')
session.get('/index/')

POST请求

requests.post()用法与requests.get()完全一致,特殊的是requests.post()多了一个data参数

1 data参数

用于存放请求体数据。content-type默认为application/x-www-form-urlencoed,此时请求体数据放于字典'form'键中

res = requests.post('http://httpbin.org/post', params={'a': ''}, data={'name': 'ethan'})
print(res.text)

2 发送json数据

此时请求体数据放于字典'data'键中

res1 = requests.post('http://httpbin.org/post', json={'name': 'ethan'})    # 没有指定请求头,默认请求头Content-Type: application/x-www-form-urlencoded
print(res1.json()) res2 = requests.post('http://httpbin.org/post', json={'age': ''}) # 默认请求头Content-Type:application/json
print(res2.json())

代理

一些网站会有相应的反爬虫措施,例如很多网站会检测某一段时间某个IP的访问次数,如果访问频率太快以至于看起来不像正常访客,它可能就会禁止这个IP的访问。所以我们需要设置一些代理服务器,每隔一段时间换一个代理,就算IP被禁止,依然可以换个IP继续爬取。

res=requests.get('http://httpbin.org/ip', proxies={'http':'110.83.40.27:9999'}).json()
print(res)

免费代理

response对象

1 常见属性

import requests
respone=requests.get('https://sh.lianjia.com/ershoufang/')
# respone属性
print(respone.text)
print(respone.content)
print(respone.status_code)
print(respone.headers)
print(respone.cookies)
print(respone.cookies.get_dict())
print(respone.cookies.items())
print(respone.url)
print(respone.history)
print(respone.encoding)

2 编码问题

requests默认编码为ISO-8859-1

res = requests.get('https://www.autohome.com.cn/beijing/')   # 该网站页面内容为gb2312编码的,如果不设置成gbk则中文乱码

# 爬取方式一
with open('autohome.html', 'wb') as f:
f.write(res.content)

# 爬取方式二
res.encoding = 'gbk'
with open("autohome.html", 'w') as f:
f.write(res.text)

3 下载二进制文件(图片,视频,音频)

res = requests.get('https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1551350578249&di=23ff7cbf4b8b47fe212e67ba3aab3267&imgtype=0&src=http%3A%2F%2Fimg.hx2cars.com%2Fupload%2Fnewimg2%2FM03%2FA9%2F03%2FClo8xFklT1GAU059AAR1t2rZPz4517_small_800_600.jpg')

with open('c180.jpg', 'wb') as f:
# f.write(res.content)
for line in res.iter_content(): # 按行写入
f.write(line)

4 解析json数据

res = requests.get('http://httpbin.org/get')
print(res.text)
print(type(res.text)) # str print(res.json())
print(type(res.json())) # dict

5 Redirection and history

默认情况下,除了requests.head,requests会自动处理所有重定向。可以使用响应对象的history方法来追踪重定向。

response.history是一个response对象的列表,为了完成请求而创建了这些对象。这个对象列表按照从最老到最近的请求进行排序

res = requests.get('http://www.jd.com/')
print(res.history) # [<Response [302]>]
print(res.text)
print(res.status_code) #

可通过allow_redirects参数禁用重定向处理:

res = requests.get('http://www.jd.com/', allow_redirects=False)
print(res.history) # []
print(res.status_code) #

02 requests模块的更多相关文章

  1. 02 请求库之 requests模块

    requests模块   一 介绍 #介绍:使用requests可以模拟浏览器的请求,比起之前用到的urllib,requests模块的api更加便捷(本质就是封装了urllib3) #注意:requ ...

  2. 爬虫requests模块 1

    让我们从一些简单的示例开始吧. 发送请求¶ 使用 Requests 发送网络请求非常简单. 一开始要导入 Requests 模块: >>> import requests 然后,尝试 ...

  3. requests 模块

    发送请求 使用Requests发送网络请求非常简单. 一开始要导入Requests模块: >>> import requests 然后,尝试获取某个网页.本例子中,我们来获取Gith ...

  4. requests模块--python发送http请求

    requests模块 在Python内置模块(urllib.urllib2.httplib)的基础上进行了高度的封装,从而使得Pythoner更好的进行http请求,使用Requests可以轻而易举的 ...

  5. Python requests模块学习笔记

    目录 Requests模块说明 Requests模块安装 Requests模块简单入门 Requests示例 参考文档   1.Requests模块说明 Requests 是使用 Apache2 Li ...

  6. Python高手之路【八】python基础之requests模块

    1.Requests模块说明 Requests 是使用 Apache2 Licensed 许可证的 HTTP 库.用 Python 编写,真正的为人类着想. Python 标准库中的 urllib2  ...

  7. Python requests模块

    import requests 下面就可以使用神奇的requests模块了! 1.向网页发送数据 >>> payload = {'key1': 'value1', 'key2': [ ...

  8. 基于python第三方requests 模块的HTTP请求类

    使用requests模块构造的下载器,首先安装第三方库requests pip install requests 1 class StrongDownload(object): def __init_ ...

  9. 使用requests模块爬虫

    虽然干技术多年了,但从没有写过博客,想来甚是惭愧,本篇作为我博客的第一篇,也是测试篇.不为写的好,只为博诸君一眸而已. 使用python爬虫,有几个比较常用的,获取html_content的模块url ...

随机推荐

  1. Tensorflow多线程输入数据处理框架(一)——队列与多线程

    参考书 <TensorFlow:实战Google深度学习框架>(第2版) 对于队列,修改队列状态的操作主要有Enqueue.EnqueueMany和Dequeue.以下程序展示了如何使用这 ...

  2. Mantis优化改造(技术篇)

    为什么要写这篇? 既然都过去这么久了,都回忆不起来了,为什么还要整理出来这篇文章呢? 这还要追溯到2018年3月份. 当时换工作,面试了国内某知名电视厂商. 简历上面写了我优化改造了bug管理系统ma ...

  3. Linux 导出Okular 编辑的pdf批注

    1.环境 ubuntu 14.04 LTS Okular Version 0.19.3 Using KDE Development Platform 4.13.3 2.方法 2.1只导出批注,不改变p ...

  4. fscanf

    fscanf (PHP 4 >= 4.0.1, PHP 5, PHP 7) fscanf — 从文件中格式化输入 说明 mixed fscanf ( resource $handle , str ...

  5. 【转】Android Support Library详细介绍

    网上对Android Support Library中各个依赖包介绍的中文资料太少了,结合官方文档和有限的参考资料做了一次总结,有描述得不对的地方还请指正. 一.主工程.依赖包.jar包.androi ...

  6. LN : leetcode 733 Flood Fill

    lc 733 Flood Fill 733 Flood Fill An image is represented by a 2-D array of integers, each integer re ...

  7. [ Luogu 3709 ] 大爷的字符串题

    \(\\\) Description 原题题面太过混乱出题人语文凉凉 给出一个长为 \(n\) 的数列 \(A\) ,多次询问: 对于一个区间 \([L_i,R_i]\),把区间内的所有数最少划分成多 ...

  8. 【学习笔记】比特(bit)、字,字节(B)存储单位之间的关系+其与操作系统位数的关系+不同编译器编译方式下数据类型的表示范围

    1.在表示网络传输速度中与表示存储单位的不同: 表示存储单位时:1kB=1024B,但在网络中表示传输速度是1KB=1000B 2.下面介绍表示存储单位时的关系及其与操作系统位数的关系: 1B=8bi ...

  9. es6语法错误

    哇,今天折腾了好久解决了一个问题,记录一下. 错误: 解决方法:配置babel,将es6语法转换成es5语法 1. 全局安装babel: npm install babel-cli -g 2. 本地安 ...

  10. 安装mysql时 make 时 提示 redeclaration of C++ built-in type ‘bool’ 错误

    安装mysql时 make 时 提示 redeclaration of C++ built-in type ‘bool’ 错误 由于gcc-c++是在./configure后进行编译的 重新./con ...