requests库的使用
- requests库的使用
pip快速安装
pip install requests
请求方法
每一个请求方法都有一个对应的API,比如GET请求就可以使用get()方法:
import requests
# 发送请求
res = requests.get('https://www.baidu.com/')
# encoding设置编码
res.encoding ='utf-8'
# text 接收返回内容
print(res.text)
而POST请求就可以使用post()方法,并且将需要提交的数据传递给data参数即可:
import requests
# 发送请求
res = requests.post('http://www.httpbin.org/post',data={'username':'q123','password':123})
# encoding设置编码
res.encoding ='utf-8'
# text 接收返回内容
print(res.text)
传递URL参数
传递URL参数也不用再像urllib中那样需要去拼接URL,而是简单的,构造一个字典,并在请求时将其传递给params参数:
import requests
# 设置参数
params = {'kay1':32324242, 'kay2':'fwewefewf232'}
# url拼接
res = requests.get(url='http://httpbin.org/get',params=params)
# 打印url
print(res.url)
自定义Headers
如果想自定义请求的Headers,同样的将字典数据传递给headers参数
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36'} res = requests.get(url='https://www.baidu.com/', headers=headers)
print(res.headers)
自定义Cookies
Requests中自定义Cookies也不用再去构造CookieJar对象,直接将字典递给cookies参数。
import requests
cookies = {'cookies_are':'working'}
res = requests.get(url='http://httpbin.org/cookies', cookies=cookies)
print(res.text)
设置代理(proxite)
当我们需要使用代理时,同样构造代理字典,传递给proxies参数。
import requests
proxite = {
'http':'http://172.0.0.1:3128',
'https':'http://172.0.0.1:3128'
}
requests.get('https://www.baidu.com/',proxite=proxite)
重定向(allow_redirects)
在网络请求中,我们常常会遇到状态码是3开头的重定向问题,在Requests中是默认开启允许重定向的,即遇到重定向时,会自动继续访问。
import requests
# 重定向(False=关闭重定向,True=开户重定向)
requests.get('https://www.baidu.com/', allow_redirects=False)
禁止证书验证(verify)
有时候我们使用了抓包工具,这个时候由于抓包工具提供的证书并不是由受信任的数字证书颁发机构颁发的,所以证书的验证会失败,所以我们就需要关闭证书验证。 在请求的时候把verify参数设置为False就可以关闭证书验证了。
import requests
# 证书验证(False=关闭验证,True=开户验证)
requests.get('https://www.baidu.com/', verify=False)
设置超时(timeout)
设置访问超时,设置timeout参数即可。
import requests
# 设置超时
requests.get('https://www.baidu.com/', timeout=0.1)
- 接收响应
响应内容(text)
通过Requests发起请求获取到的,是一个requests.models.Response对象。通过这个对象我们可以很方便的获取响应的内容。
之前通过urllib获取的响应,读取的内容都是bytes的二进制格式,需要我们自己去将结果decode()一次转换成字符串数据。
而Requests通过text属性,就可以获得字符串格式的响应内容。
import requests
# 接收响应内容
res = requests.get('https://www.baidu.com/')
print(res.text)
字符编码(encoding)
Requests会自动的根据响应的报头来猜测网页的编码是什么,然后根据猜测的编码来解码网页内容,基本上大部分的网页都能够正确的被解码。而如果发现text解码不正确的时候,就需要我们自己手动的去指定解码的编码格式。
import requests
# 字符编码
res = requests.get('https://www.baidu.com/')
res.encoding = 'utf-8'
print(res.text)
二进制数据(content)
而如果你需要获得原始的二进制数据,那么使用content属性即可。
import requests
# 二进制数据
res = requests.get('https://www.baidu.com/')
print(res.content)
json数据(json)
如果我们访问之后获得的数据是JSON格式的,那么我们可以使用json()方法,直接获取转换成字典格式的数据。
import requests res = requests.get('https://api.github.com/events')
# 转换为json数据
res.json()
print(res.text)
状态码(status_code)
通过status_code属性获取响应的状态码
import requests
res = requests.get('https://api.github.com/events')
print(res.status_code)
响应报头(headers)
通过headers属性获取响应的报头
import requests
res = requests.get('https://api.github.com/events')
print(res.headers)
服务器返回的cookies(cookies)
通过cookies属性获取服务器返回的cookies
import requests
res = requests.get('https://api.github.com/events')
print(res.cookies)
url
还可以使用url属性查看访问的url。
import requests
res = requests.get('https://api.github.com/events')
print(res.url)
- Session对象
在Requests中,实现了Session(会话)功能,当我们使用Session时,能够像浏览器一样,在没有关闭关闭浏览器时,能够保持住访问的状态。 这个功能常常被我们用于登陆之后的数据获取,使我们不用再一次又一次的传递cookies。
首先我们需要去生成一个Session对象,然后用这个Session对象来发起访问,发起访问的方法与正常的请求是一摸一样的。 同时,需要注意的是,如果是我们在get()方法中传入headers和cookies等数据,那么这些数据只在当前这一次请求中有效。如果你想要让一个headers在Session的整个生命周期内都有效的话,需要用以下的方式来进行设置:
import requests
# 发送请求
res = requests.get('https://api.github.com/events')
# 创建session实例
session = requests.Session()
# 用session发送请求
resp = session.get('https://api.github.com/events')
print(resp.text)
- 爬虫例子
爬取铃声:
import requests
from lxml import etree
# 用户输入要爬取的页码
load =input('请输入您需要下载的页码:')
# 发送请求并以二进制读取数据
mp3_url =requests.get('http://ring.itools.cn/index.php?m=applist&gid=zuire&page=%s'%load).content.decode()
# 解析下载的数据(转换为html)
html = etree.HTML(mp3_url)
# 用xpath获得铃声的链接
html_data = mp3_url.xpath('//div/a/@lurl')
# 循环取列表中的链接
for url in html_data:
# 发送铃声的链接以二是制获取铃声的内容
url_go = requests.get(url).content
# 分割链接,用以命名
name = url.split('/')[-1]
# 打开文件
with open('mp3/%s'%name,'wb') as f:
f.write(url_go)
print('下载完成:',name) print('已经全部下载完成')
豆瓣登录案例:
import requests
# 登录页面
img_url='https://accounts.douban.com/j/mobile/login/basic'
# 添加请求头
headers ={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
}
# 发送登录信息,登录信息在浏览器F12中查找或在抓包工具中获得
data ={
'ck': '5oo_',
'name': '1598959****',
'password': 'q12322333',
'remember': 'false'
}
# 发送登录信息到服务器
imges=requests.post(img_url,data=data,verify=False,headers=headers)
# 接收服务器返回的cookies
cookies =imges.cookies
# 发送请求
idex =requests.get('https://www.douban.com/',headers=headers,cookies=cookies)
print(idex.text)
糗事百科信息提取案例:
import re
import requests
# 用户输入采集页面
page = input('输入收集的页面:')
# 设置请求头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
'Referer': 'https://www.qiushibaike.com/hot/page/1/'
}
# 发送请求并读取返回的内容
res =requests.get('https://www.qiushibaike.com/hot/page/%s/'%page,headers=headers,verify=False).text
# 用re模块提取想要的信息
user = re.findall(r"id='qiushi_tag_1(.*?)'>",res,re.S)
# 拼接链接
url =['https://www.qiushibaike.com/article/'+url for url in user]
for i in url:
# 发送请求
user_url =requests.get(i,headers=headers).text
# 用re模块提取想要的信息
name= re.findall(r'<h1 class="article-title">\n(.*?)的糗事:',user_url,re.S)[0]
tim = re.findall(r'<span class="stats-time">\n(.*?)\n</span>',user_url,re.S)[0]
content =re.findall(r'<div class="content">(.*?)</div>',user_url,re.S)[0]
print('用户:',name.strip())
print('发布时间:',tim)
print(content,'\n')
3
requests库的使用的更多相关文章
- Python爬虫小白入门(二)requests库
一.前言 为什么要先说Requests库呢,因为这是个功能很强大的网络请求库,可以实现跟浏览器一样发送各种HTTP请求来获取网站的数据.网络上的模块.库.包指的都是同一种东西,所以后文中可能会在不同地 ...
- Requests库上传文件时UnicodeDecodeError: 'ascii' codec can't decode byte错误解析
在使用Request上传文件的时候碰到如下错误提示: 2013-12-20 20:51:09,235 __main__ ERROR 'ascii' codec can't decode byte 0x ...
- Requests库的几种请求 - 通过API操作Github
本文内容来源:https://www.dataquest.io/mission/117/working-with-apis 本文的数据来源:https://en.wikipedia.org/wiki/ ...
- python脚本实例002- 利用requests库实现应用登录
#! /usr/bin/python # coding:utf-8 #导入requests库 import requests #获取会话 s = requests.session() #创建登录数据 ...
- 大概看了一天python request源码。写下python requests库发送 get,post请求大概过程。
python requests库发送请求时,比如get请求,大概过程. 一.发起get请求过程:调用requests.get(url,**kwargs)-->request('get', url ...
- python WEB接口自动化测试之requests库详解
由于web接口自动化测试需要用到python的第三方库--requests库,运用requests库可以模拟发送http请求,再结合unittest测试框架,就能完成web接口自动化测试. 所以笔者今 ...
- python爬虫从入门到放弃(四)之 Requests库的基本使用
什么是Requests Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库如果你看过上篇文章关于urllib库的使用,你会发现,其 ...
- (转)Python爬虫利器一之Requests库的用法
官方文档 以下内容大多来自于官方文档,本文进行了一些修改和总结.要了解更多可以参考 官方文档 安装 利用 pip 安装 $ pip install requests 或者利用 easy_install ...
- python requests库学习笔记(上)
尊重博客园原创精神,请勿转载! requests库官方使用手册地址:http://www.python-requests.org/en/master/:中文使用手册地址:http://cn.pytho ...
- 使用Python的requests库进行接口测试——session对象的妙用
from:http://blog.csdn.net/liuchunming033/article/details/48131051 在进行接口测试的时候,我们会调用多个接口发出多个请求,在这些请求中有 ...
随机推荐
- code1540 银河英雄传说
pa[i]代表i的father pre[i]代表i之前有多少个 sum[i]代表i所在的整列有多少个 cc为命令类型,x y为命令参数, fx fy分别为x y的father 当cc==‘M’时,合并 ...
- logback与log4j比较
摘自:https://www.cnblogs.com/smile361/p/7592684.html logback与log4j比较 更快的执行速度: 基于我们先前在log4j上的工作,logback ...
- python 学习之路开始了
python 学习之路开始了.....记录点点滴滴....
- [GO]等待时间的使用
package main import ( "time" "fmt" ) func main() { <-time.After(*time.Second) ...
- Transferring Data Between ASP.NET Web Pages
14 July 2012 20:24 http://www.mikesdotnetting.com/article/192/transferring-data-between-asp-net-web- ...
- 设计模式6---代理模式(Proxy Pattern)
代理设计模式 定义:为其他对象提供一种代理以控制对这个对象的访问. 1. 静态代理 静态代理在使用时,需要定义接口或者父类,被代理对象与代理对象都实现相同的接口或者是继承相同父类. 接口:IUser ...
- Inno Setup 通用脚本及简要说明( 一般情况够用了)
;以下脚本主要完成创建开始菜单和桌面的快捷方式,目录安装. #define MyAppName "我的软件名" #define MyAppVersion "1.0&quo ...
- Linux Guard Service - 守护进程分裂
分裂守护进程 由于fork()后第一行仍然在循环中,使用fork()返回值鉴别当前进程的性质 int i = 0; for (i = 0; i < 10; i++) { // sleep(1); ...
- RobotFramework做接口自动化(内部接口需要登录token)
背景: 项目中需要做接口自动化测试,使用robot,有一个收货地址列表的接口直接传参数访问时会返回:{"msg":"缺少参数","code" ...
- Robot Framework资料
https://www.cnblogs.com/pachongshangdexuebi/category/981644.html 虫师 :http://www.cnblogs.com/fnng/ ...