爬虫系列(七) 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) 呢?可以用下面的一句话简单概括: 正则表达式是一组特殊的 字符序列,由一些事先定义好的字符以及这些字符的组合形成,常常用于 匹 ...
随机推荐
- poj 3468 A Simple Problem with Integers(线段树+区间更新+区间求和)
题目链接:id=3468http://">http://poj.org/problem? id=3468 A Simple Problem with Integers Time Lim ...
- 使用Win32 API实现生产者消费者线程同步
使用win32 API创建线程,创建信号量用于线程的同步 创建信号量 语法例如以下 HANDLE semophore; semophore = CreateSemaphore(lpSemaphoreA ...
- 一篇文章贯穿ACE各种发送接收组件 1.2版
TCP通信过程介绍 首先介绍一下socket通信的基本过程:这里先如果有两个家伙在通信,一个是S.还有一个叫C (1)S打开port监听本地的port看看有没有人来连接: (2)与此同一时候C试图去连 ...
- MySql 同一个列中的内容进行批量改动
问题重现: MySql 数据库中,一给列的内容中包含 ".wmv" 须要将 "." 后的wmv格式 换为"flv" 解决的方法 up ...
- 试试pypy
pypy是一个python的解释器和JIT编译器.能够在不改动不论什么代码的情况下大幅提升python代码的性能. 使用超级简单,在官网下载编译好的二进制包进行安装,然后然后执行代码的时候指定这个解释 ...
- HDU5489 LIS变形
Removed Interval Problem Description Given a sequence of numbers A=a1,a2,…,aN , a subsequence b1,b2, ...
- yum install tomcat
安装tomcat6 yum install tomcat6 tomcat6-webapps tomcat6-admin-webapps 启动tomcat6 service tomcat6 start ...
- axis2的wsdl无法使用eclipse axis1插件来生成client--解决方法
使用jetty+axis2实现webservice服务端,且无需使用axis2命令生成服务端代码.仅仅要services.xml配置实现类. project为gradleproject配置文件在src ...
- LINQ Query Expressions
https://msdn.microsoft.com/en-us/library/bb397676(v=vs.100).aspx Language-Integrated Query (LINQ) is ...
- hdu 1213(并查集模版题)
How Many Tables Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)T ...