爬虫(三):Requests库的基本使用
一:什么是Requests
Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库
如果你看过上篇文章关于urllib库的使用,你会发现,其实urllib还是非常不方便的,而Requests它会比urllib更加方便,可以节约我们大量的工作。(用了requests之后,你基本都不愿意用urllib了)一句话,requests是python实现的最简单易用的HTTP库,建议爬虫使用requests库。
默认安装好python之后,是没有安装requests模块的,需要单独通过pip安装
二:Requests功能详解
实例引入:
import requests
response = requests.get('https://www.baidu.com/')
# 添加编码方式,解决乱码问题
response.encoding=response.apparent_encoding
# response.encoding="utf-8"
print(type(response))
print(response.status_code) # 状态码
print(type(response.text))
print(response.text) # 响应的文本内容
print(response.cookies) # 响应的cookie
各种请求方式:
import requests
requests.get('https://www.baidu.com/') # get
requests.post('http://httpbin.org/post') # 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请求
import requests
response = requests.get('http://httpbin.org/get')
print(response.text)
带参数的GET请求
# 方式一
import requests
# 直接加在url后面
response = requests.get("http://httpbin.org/get?name=germey&age=22")
print(response.text) # 方式二
import requests data = {
'name': 'germey',
'age': 22
}
# 通过params来传递data
response = requests.get("http://httpbin.org/get", params=data)
print(response.text) # 上述两种的结果是相同的,通过params参数传递一个字典内容,从而直接构造url
# 注意:第二种方式通过字典的方式的时候,如果字典中的参数为None则不会添加到url上
解析json
import requests
import json response = requests.get("http://httpbin.org/get")
print(type(response.text))
print(response.json()) # 实际上是执行了json.loads(response.text)
print(json.loads(response.text))
print(type(response.json()))
获取二进制数据
import requests # 获取并打印二进制数据
response = requests.get("https://github.com/favicon.ico")
print(type(response.text), type(response.content))
print(response.text)
print(response.content) # 获取二进制数据并存入文件,通常如视频,图片,音乐等
response = requests.get("https://github.com/favicon.ico")
with open('favicon.ico', 'wb') as f:
f.write(response.content)
f.close()
添加headers
# 有些网站必须要带头部信息才能正常访问
import requests headers = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36'
}
response = requests.get("https://www.zhihu.com/explore", headers=headers)
print(response.text)
基本POST请求
import requests
data = {'name': 'germey', 'age': ''} # 通过字典类型构造
response = requests.post("http://httpbin.org/post", data=data)
print(response.text)
响应
reponse属性
import requests
response = requests.get('http://www.jianshu.com')
print(type(response.status_code), response.status_code) # 状态码
print(type(response.headers), response.headers) # 头信息
print(type(response.cookies), response.cookies) # cookies
print(type(response.url), response.url) # url
print(type(response.history), response.history) # 访问列表
状态码判断:--》状态码大全
100: ('continue',),
101: ('switching_protocols',),
102: ('processing',),
103: ('checkpoint',),
122: ('uri_too_long', 'request_uri_too_long'),
200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'),
201: ('created',),
202: ('accepted',),
203: ('non_authoritative_info', 'non_authoritative_information'),
204: ('no_content',),
205: ('reset_content', 'reset'),
206: ('partial_content', 'partial'),
207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),
208: ('already_reported',),
226: ('im_used',),
# Redirection.
300: ('multiple_choices',),
301: ('moved_permanently', 'moved', '\\o-'),
302: ('found',),
303: ('see_other', 'other'),
304: ('not_modified',),
305: ('use_proxy',),
306: ('switch_proxy',),
307: ('temporary_redirect', 'temporary_moved', 'temporary'),
308: ('permanent_redirect',
'resume_incomplete', 'resume',), # These 2 to be removed in 3.0
# Client Error.
400: ('bad_request', 'bad'),
401: ('unauthorized',),
402: ('payment_required', 'payment'),
403: ('forbidden',),
404: ('not_found', '-o-'),
405: ('method_not_allowed', 'not_allowed'),
406: ('not_acceptable',),
407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),
408: ('request_timeout', 'timeout'),
409: ('conflict',),
410: ('gone',),
411: ('length_required',),
412: ('precondition_failed', 'precondition'),
413: ('request_entity_too_large',),
414: ('request_uri_too_large',),
415: ('unsupported_media_type', 'unsupported_media', 'media_type'),
416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
417: ('expectation_failed',),
418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
421: ('misdirected_request',),
422: ('unprocessable_entity', 'unprocessable'),
423: ('locked',),
424: ('failed_dependency', 'dependency'),
425: ('unordered_collection', 'unordered'),
426: ('upgrade_required', 'upgrade'),
428: ('precondition_required', 'precondition'),
429: ('too_many_requests', 'too_many'),
431: ('header_fields_too_large', 'fields_too_large'),
444: ('no_response', 'none'),
449: ('retry_with', 'retry'),
450: ('blocked_by_windows_parental_controls', 'parental_controls'),
451: ('unavailable_for_legal_reasons', 'legal_reasons'),
499: ('client_closed_request',),
# Server Error.
500: ('internal_server_error', 'server_error', '/o\\', '✗'),
501: ('not_implemented',),
502: ('bad_gateway',),
503: ('service_unavailable', 'unavailable'),
504: ('gateway_timeout',),
505: ('http_version_not_supported', 'http_version'),
506: ('variant_also_negotiates',),
507: ('insufficient_storage',),
509: ('bandwidth_limit_exceeded', 'bandwidth'),
510: ('not_extended',),
511: ('network_authentication_required', 'network_auth', 'network_authentication'),
三:requests高级操作
文件上传
import requests
# 通过files参数上传,必须以二进制读取
files = {'file': open('favicon.ico', 'rb')}
response = requests.post("http://httpbin.org/post", files=files)
print(response.text)
获取cookie
import requests
response = requests.get("https://www.baidu.com")
print(response.cookies)
for key, value in response.cookies.items():
print(key + '=' + value)
会话维持
# cookie的一个作用就是可以用于模拟登陆,做会话维持
import requests s = requests.Session() # 通过session对象来维持cookie
s.get('http://httpbin.org/cookies/set/number/123456789')
response = s.get('http://httpbin.org/cookies')
print(response.text)
证书验证
# 现在的很多网站都是https的方式访问,所以这个时候就涉及到证书的问题 import requests
from requests.packages import urllib3
urllib3.disable_warnings() # 取消警告(可以不要)
# 取消证书验证,默认是验证证书,如果证书不合法会报错
response = requests.get('https://www.12306.cn', verify=False)
print(response.status_code)
代理设置
import requests
proxies = {
"http": "http://127.0.0.1:9743",
"https": "https://127.0.0.1:9743",
}
# 通过proxies来设置代理
response = requests.get("https://www.taobao.com", proxies=proxies)
print(response.status_code)
‘‘‘
# 如果代理需要设置用户名和密码,则将字典改写成
proxies = {
"http":"http://user:password@127.0.0.1:9999"
}
# 如果代理是通过sokces这种方式,则需要:
pip install "requests[socks]" # 安装模块
proxies= {
"http":"socks5://127.0.0.1:9999",
"https":"sockes5://127.0.0.1:8888"
}
’’’
超时设置
import requests
from requests.exceptions import ReadTimeout
try:
# 通过timeout参数设置超时的时间
response = requests.get("http://httpbin.org/get", timeout = 0.5)
print(response.status_code)
except ReadTimeout:
print('Timeout')
认证设置
# 如果碰到需要认证的网站可以通过requests.auth模块实现
# 方式一
import requests
from requests.auth import HTTPBasicAuth r = requests.get('http://120.27.34.24:9001', auth=HTTPBasicAuth('user', ''))
print(r.status_code) # 方式二
import requests r = requests.get('http://120.27.34.24:9001', auth=('user', ''))
print(r.status_code)
import requests
from requests.exceptions import ReadTimeout, ConnectionError, RequestException
try:
response = requests.get("http://httpbin.org/get", timeout = 0.5)
print(response.status_code)
except ReadTimeout:
print('Timeout')
except ConnectionError:
print('Connection error')
except RequestException:
print('Error')
爬虫(三):Requests库的基本使用的更多相关文章
- PYTHON 爬虫笔记三:Requests库的基本使用
知识点一:Requests的详解及其基本使用方法 什么是requests库 Requests库是用Python编写的,基于urllib,采用Apache2 Licensed开源协议的HTTP库,相比u ...
- Python爬虫之requests库介绍(一)
一:Requests: 让 HTTP 服务人类 虽然Python的标准库中 urllib2 模块已经包含了平常我们使用的大多数功能,但是它的 API 使用起来让人感觉不太好,而 Requests 自称 ...
- 爬虫相关--requests库
requests的理想:HTTP for Humans 一.八个方法 相比较urllib模块,requests模块要简单很多,但是需要单独安装: 在windows系统下只需要在命令行输入命令 pip ...
- Python爬虫之requests库的使用
requests库 虽然Python的标准库中 urllib模块已经包含了平常我们使用的大多数功能,但是它的 API 使用起来让人感觉不太好,而 Requests宣传是 "HTTP for ...
- python爬虫之requests库
在python爬虫中,要想获取url的原网页,就要用到众所周知的强大好用的requests库,在2018年python文档年度总结中,requests库使用率排行第一,接下来就开始简单的使用reque ...
- python网络爬虫之requests库
Requests库是用Python编写的HTTP客户端.Requests库比urlopen更加方便.可以节约大量的中间处理过程,从而直接抓取网页数据.来看下具体的例子: def request_fun ...
- Python爬虫:requests 库详解,cookie操作与实战
原文 第三方库 requests是基于urllib编写的.比urllib库强大,非常适合爬虫的编写. 安装: pip install requests 简单的爬百度首页的例子: response.te ...
- 爬虫入门 requests库
写在最前的具体资料: https://2.python-requests.org//zh_CN/latest/user/quickstart.html https://www.liaoxuefeng. ...
- 【Python爬虫】爬虫利器 requests 库小结
requests库 Requests 是一个 Python 的 HTTP 客户端库. 支持许多 HTTP 特性,可以非常方便地进行网页请求.网页分析和处理网页资源,拥有许多强大的功能. 本文主要介绍 ...
- 爬虫值requests库
requests简介 简介 Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库 ,使用起来比urllib简洁很多 因为是第三方库, ...
随机推荐
- [v]Windows下Git安装指南
参考<Git权威指南>安装整理,图书配套网址参见[1] 1. Cygwin下安装配置Git 1. 在Windows下安装配置Git有2种不同的方案 (1)msysGit, (2)Cygwi ...
- SQL Sever 刪除重複數據只剩一條
use book go create table ##T1( n int, a nvarchar(20) ) --查詢重複記錄,插入臨時表 insert into ##T1(n,a) select s ...
- 【转载】C#将字符串中字母全部转换为大写或者小写
在C#的编程开发过程中,有时候判断字符串是否相等时,并不关注字母的大小写,此时在C#中可以使用ToUpper方法将字符串中所有的字母转换为大写,使用ToLower方法可以将字符串中所有字母转换为小写. ...
- React Native 开发豆瓣评分(一)环境搭建&配置模拟器
详细可参考 官方文档,这里进记录一些重要过程. 安装环境 下载 Android Studio 选择 Custom 进行安装: Android SDK Android SDK Platform Perf ...
- iOS NSString使用stringWithFormat的拼接
##保留2位小数点## //.2代表小数点后面保留2位(2代表保留的数量) NSString *string = [NSString stringWithFormat:@"%.2f" ...
- TCP与UDP协议必知必会
TCP协议 一个工作在传输层的传输控制协议,面向连接.可靠的流式协议,HTTP协议建立在TCP基础上.每个TCP报文,实际在网络层进行封装成IP数据报,会进行IP分片(受限于MTU). 头部(20字节 ...
- java数据类型转换的常见方法
public class Testfun { public static void main(String[] args) { // (一)跨Number父类的类型转换 // 1.str转int =& ...
- MySql 学习之 一条更新sql的执行过程
上一篇文章咱们说了一条查询sql的执行过程.如果没有看过上一篇文章的可以去看下上一篇文章,今天咱们说说一条更新sql的执行过程. 上面一条sql是将id为1的分数加上10. 那么它的执行流程是怎样的呢 ...
- c# 属性说明
- lvs+keepalived集群架构服务
一,LVS功能详解 1.1 LVS(Linux Virtual Server)介绍 LVS是Linux Virtual Server 的简写(也叫做IPVS),意即Linux虚拟服务器,是一个虚拟的服 ...