爬虫系列(七) requests的基本使用
一、requests 简介
requests 是一个功能强大、简单易用的 HTTP 请求库,可以使用 pip install requests 命令进行安装
下面我们将会介绍 requests 中常用的方法,详细内容请参考 官方文档
二、requests 使用
在开始讲解前,先给大家提供一个用于测试的网站,http://www.httpbin.org/
这个网站可以在页面上返回所发送 请求 的相关信息,十分适合练习使用
好了,下面正式开始!
1、get 方法
该方法用于向目标网址发送请求,接收响应
该方法返回一个 Response 对象,其常用的属性和方法列举如下:
- response.url:返回请求网站的 URL
- response.status_code:返回响应的状态码
- response.encoding:返回响应的编码方式
- response.cookies:返回响应的 Cookie 信息
- response.headers:返回响应头
- response.content:返回 bytes 类型的响应体
- response.text:返回 str 类型的响应体,相当于
response.content.decode('utf-8') - response.json():返回 dict 类型的响应体,相当于
json.loads(response.text)
>>> import requests
>>> response = requests.get('http://www.httpbin.org/get')
>>> type(response)
# <class 'requests.models.Response'>
>>> print(response.url) # 返回请求网站的 URL
# http://www.httpbin.org/get
>>> print(response.status_code) # 返回响应的状态码
# 200
>>> print(response.encoding) # 返回响应的编码方式
# None
>>> print(response.cookies) # 返回响应的 Cookie 信息
# <RequestsCookieJar[]>
>>> print(response.headers) # 返回响应头
# {'Connection': 'keep-alive', 'Server': 'gunicorn/19.9.0', 'Date': 'Sat, 18 Aug 2018 02:00:23 GMT', 'Content-Type': 'application/json', 'Content-Length': '275', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', 'Via': '1.1 vegur'}
>>> type(response.content) # 返回 bytes 类型的响应体
# <class 'bytes'>
>>> type(response.text) # 返回 str 类型的响应体
# <class 'str'>
>>> type(response.json()) # 返回 dict 类型的响应体
# <class 'dict'>
该方法的参数说明如下:
url:必填,指定请求 URL
params:字典类型,指定请求参数,常用于发送 GET 请求时使用
>>> import requests
>>> url = 'http://www.httpbin.org/get'
>>> params = {
'key1':'value1',
'key2':'value2'
}
>>> response = requests.get(url=url,params=params)
>>> print(response.text)
# {
# "args": { # 我们设定的请求参数
# "key1": "value1",
# "key2": "value2"
# },
# "headers": {
# "Accept": "*/*",
# "Accept-Encoding": "gzip, deflate",
# "Connection": "close",
# "Host": "www.httpbin.org",
# "User-Agent": "python-requests/2.19.1"
# },
# "origin": "110.64.88.141",
# "url": "http://www.httpbin.org/get?key1=value1&key2=value2"
# }
data:字典类型,指定表单信息,常用于发送 POST 请求时使用
注意:此时应该使用 post 方法,只需要简单的将 get 替换成 post 即可
>>> import requests
>>> url = 'http://www.httpbin.org/post'
>>> data = {
'key1':'value1',
'key2':'value2'
}
>>> response = requests.post(url=url,data=data)
>>> print(response.text)
# {
# "args": {},
# "data": "",
# "files": {},
# "form": { # 我们设定的表单数据
# 'key1': 'value1',
# 'key2': 'value2'
# },
# "headers": {
# "Accept": "*/*",
# "Accept-Encoding": "gzip, deflate",
# "Connection": "close",
# "Content-Length": "17",
# "Content-Type": "application/x-www-form-urlencoded",
# "Host": "www.httpbin.org",
# "User-Agent": "python-requests/2.19.1"
# },
# "json": null,
# "origin": "116.16.107.178",
# "url": "http://www.httpbin.org/post"
# }
headers:字典类型,指定请求头部
>>> import requests
>>> url = 'http://www.httpbin.org/headers'
>>> headers = {
'USER-AGENT':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}
>>> response = requests.get(url=url,headers=headers)
>>> print(response.text)
# {
# "headers": {
# "Accept": "*/*",
# "Accept-Encoding": "gzip, deflate",
# "Connection": "close",
# "Host": "www.httpbin.org",
# "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36" # 我们设定的请求头部
# }
# }
proxies:字典类型,指定使用的代理
>>> import requests
>>> url = 'http://www.httpbin.org/ip'
>>> proxies = {
'http':'182.88.178.128:8123',
'http':'61.135.217.7:80'
}
>>> response = requests.get(url=url,proxies=proxies)
>>> print(response.text)
# {
# "origin": "182.88.178.128"
# }
cookies:字典类型,指定 Cookie
>>> import requests
>>> url = 'http://www.httpbin.org/cookies'
>>> cookies = {
'name1':'value1',
'name2':'value2'
}
>>> response = requests.get(url=url,cookies=cookies)
>>> print(response.text)
# {
# "cookies": {
# "name1": "value1",
# "name2": "value2"
# }
# }
auth:元组类型,指定登陆时的账号和密码
>>> import requests
>>> url = 'http://www.httpbin.org/basic-auth/user/password'
>>> auth = ('user','password')
>>> response = requests.get(url=url,auth=auth)
>>> print(response.text)
# {
# "authenticated": true,
# "user": "user"
# }
verify:布尔类型,指定请求网站时是否需要进行证书验证,默认为 True,表示需要证书验证
假如不希望进行证书验证,则需要设置为 False
>>> import requests
>>> response = requests.get(url='https://www.httpbin.org/',verify=False)
但是在这种情况下,一般会出现 Warning 提示,因为 Python 希望我们能够使用证书验证
如果不希望看到 Warning 信息,可以使用以下命令消除
>>> requests.packages.urllib3.disable_warnings()
timeout:指定超时时间,若超过指定时间没有获得响应,则抛出异常
2、exceptions 模块
exceptions 是 requests 中负责异常处理的模块,包含下面常见的异常类:
- Timeout:请求超时
- ConnectionError:网络问题,例如 DNS 故障,拒绝连接等
- TooManyRedirects:请求超过配置的最大重定向数
注意 :所有显式抛出的异常都继承自 requests.exceptions.RequestException
>>> import requests
>>> try:
response = requests.get('http://www.httpbin.org/get', timeout=0.1)
except requests.exceptions.RequestException as e:
if isinstance(e,requests.exceptions.Timeout):
print("Time out")
# Time out
【参考资料】
【爬虫系列相关文章】
爬虫系列(七) requests的基本使用的更多相关文章
- 爬虫系列之requests
爬取百度内容: import requests url = "https://www.baidu.com" if __name__ == '__main__': try: kv = ...
- 爬虫系列(八) 用requests实现天气查询
这篇文章我们将使用 requests 调用天气查询接口,实现一个天气查询的小模块,下面先贴上最终的效果图 1.接口分析 虽然现在网络上有很多免费的天气查询接口,但是有很多网站都是需要注册登陆的,过程比 ...
- 爬虫系列(十) 用requests和xpath爬取豆瓣电影
这篇文章我们将使用 requests 和 xpath 爬取豆瓣电影 Top250,下面先贴上最终的效果图: 1.网页分析 (1)分析 URL 规律 我们首先使用 Chrome 浏览器打开 豆瓣电影 T ...
- 爬虫系列(十一) 用requests和xpath爬取豆瓣电影评论
这篇文章,我们继续利用 requests 和 xpath 爬取豆瓣电影的短评,下面还是先贴上效果图: 1.网页分析 (1)翻页 我们还是使用 Chrome 浏览器打开豆瓣电影中某一部电影的评论进行分析 ...
- 爬虫系列(三) urllib的基本使用
一.urllib 简介 urllib 是 Python3 中自带的 HTTP 请求库,无需复杂的安装过程即可正常使用,十分适合爬虫入门 urllib 中包含四个模块,分别是 request:请求处理模 ...
- 爬虫系列(九) xpath的基本使用
一.xpath 简介 究竟什么是 xpath 呢?简单来说,xpath 就是一种在 XML 文档中查找信息的语言 而 XML 文档就是由一系列节点构成的树,例如,下面是一份简单的 XML 文档: &l ...
- 爬虫系列(二) Chrome抓包分析
在这篇文章中,我们将尝试使用直观的网页分析工具(Chrome 开发者工具)对网页进行抓包分析,更加深入的了解网络爬虫的本质与内涵 1.测试环境 浏览器:Chrome 浏览器 浏览器版本:67.0.33 ...
- 爬虫系列(四) 用urllib实现英语翻译
这篇文章我们将以 百度翻译 为例,分析网络请求的过程,然后使用 urllib 编写一个英语翻译的小模块 1.准备工作 首先使用 Chrome 浏览器打开 百度翻译,这里,我们选择 Chrome 浏览器 ...
- 爬虫系列(五) re的基本使用
1.简介 究竟什么是正则表达式 (Regular Expression) 呢?可以用下面的一句话简单概括: 正则表达式是一组特殊的 字符序列,由一些事先定义好的字符以及这些字符的组合形成,常常用于 匹 ...
随机推荐
- [Android L or M ]解除SwitchPreference与Preference的绑定事件
需求描写叙述 默认情况,Android的两个控件SwitchPreference和CheckBoxPreference的事件处理是和Preference整个区域的事件绑定在一起的,然而,有时须要将其事 ...
- Servlet仿CSDN动态验证码的生成-带数字和字母
林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 一.实现的思路: (1)首先,须要创建一个Servlet.该Servlet通过字节型响应给cl ...
- NDK编译库执行时报dlopen failed: cannot locate symbol "__exidx_end" 解决的方法
当用NDK编译的库在执行载入时报例如以下错: dlopen("/data/data/xxx.xxx.xxx/lib/libxxx.so") failed: dlopen faile ...
- hdu 4941 Magical Forest (map容器)
Magical Forest Time Limit: 24000/12000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Other ...
- CodeForces - 743D Chloe and pleasant prizes
Chloe and pleasant prizes time limit per test 2 seconds memory limit per test 256 megabytes input st ...
- hdu 1075(字典树)
What Are You Talking About Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 102400/204800 K ...
- poj 1061(扩展欧几里得定理求不定方程)
两只青蛙在网上相识了,它们聊得很开心,于是觉得很有必要见一面.它们很高兴地发现它们住在同一条纬度线上,于是它们约定各自朝西跳,直到碰面为止.可是它们出发之前忘记了一件很重要的事情,既没有问清楚对方的特 ...
- python使用MySQLdb向mySQL批量插入数据的方法
该功能通过调用mySQLdb python库中的 cursor.executemany()函数完成批量处理. 今天用这个函数完成了批量插入 例程: def test_insertDB(options) ...
- Winform 异步调用
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...
- python修改植物僵尸
import win32process#进程模块 import win32con#系统定义 import win32api#调用系统模块 import ctypes#C语言类型 import win3 ...