requests模块

Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库,Requests它会比urllib更加方便,requests是python实现的最简单易用的HTTP库,建议爬虫使用requests库。

1.安装:

  pip install requests

2.基本语法

  1.request模块支持的请求:

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 基本请求

import requests
response=requests.get('https://www.jd.com/',) with open("jd.html","wb") as f:
f.write(response.content)

2 含参数请求

import requests
response=requests.get('https://s.taobao.com/search?q=手机')
response=requests.get('https://s.taobao.com/search',params={"q":"美女"})

3 含请求头请求

mport requests
response=requests.get('https://dig.chouti.com/',
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.75 Safari/537.36',
}
)

4 含cookies请求

import uuid     # 生成随机字符串的模块
import requests url = 'http://httpbin.org/cookies'
cookies = dict(sbid=str(uuid.uuid4())) res = requests.get(url, cookies=cookies)
print(res.text) # cookie 的用法 :
res =requests.get("https://www.autohome.com.cn/beijing/")
res_cookies=res.cookies
requests.post("https://www.autohome.com.cn/beijing/",cookies=res_cookies)

5.session请求

# 相当于上面cookie的用法过程
session=requests.session()
res1 = session.gett("https://github.com/login/")
res2 =session.post("https://github.com/session",headers=header,data=data)

post请求

1 data参数
requests.post()用法与requests.get()完全一致,特殊的是requests.post()多了一个data参数,用来存放请求体数据 

response=requests.post("http://httpbin.org/post",params={"a":"1"}, data={"name":"deng"}) 

2 发送json数据

mport requests
res1=requests.post(url='http://httpbin.org/post', data={'name':'deng'}) #没有指定请求头,#默认的请求头:application/x-www-form-urlencoed
print(res1.json()) res2=requests.post(url='http://httpbin.org/post',json={'age':"11",}) #默认的请求头:application/json
print(res2.json())

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) # i cookies
print(respone.cookies.get_dict())
print(respone.cookies.items())
print(respone.url)
print(respone.history) # 重定向之前的
print(respone.encoding) # 编码

(2) 编码问题

import requests
response=requests.get('http://www.autohome.com/news')
#response.encoding='gbk' #汽车之家网站返回的页面内容为gb2312编码的,而requests的默认编码为ISO-8859-1,如果不设置成gbk则中文乱码
with open("res.html","w") as f:
f.write(response.text)

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

import requests
response=requests.get('http://bangimg1.dahe.cn/forum/201612/10/200447p36yk96im76vatyk.jpg')
with open("res.png","wb") as f:
# f.write(response.content) # 比如下载视频时,如果视频100G,用response.content然后一下子写到文件中是不合理的
for line in response.iter_content(): # 生成器
f.write(line)

(4) 解析json数据

import requests
import json response=requests.get('http://httpbin.org/get')
res1=json.loads(response.text) #太麻烦
res2=response.json() #直接获取json数据
print(res1==res2)

(5) Redirection and History

默认情况下,除了 HEAD, Requests 会自动处理所有重定向。可以使用响应对象的 history 方法来追踪重定向。Response.history 是一个 Response 对象的列表,为了完成请求而创建了这些对象。这个对象列表按照从最老到最近的请求进行排序。

>>> r = requests.get('http://github.com')
>>> r.url
'https://github.com/'
>>> r.status_code
200
>>> r.history
[<Response [301]>]

另外,还可以通过 allow_redirects 参数禁用重定向处理:

>>> r = requests.get('http://github.com', allow_redirects=False)
>>> r.status_code
301
>>> r.history
[] 

requests进阶用法

代理

快代理:  https://www.kuaidaili.com/free/

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

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

爬虫案例

github的home页

#解决问题的思路:
#先用自己的账户登录GitHub ,去找需要带上的请求信息
#分析需要带上的请求信息,此处最关键的点是:登录时将数据提交到哪个url ,数据中authenticity_token 如何动态获取 # 获取登录页面
url ='https://github.com/login' # 登录地址
session=requests.session()
login = session.get(url) # 构建数据
authenticity_token=re.findall('name="authenticity_token" value="(.*?)"',login.text)
data={
'commit': 'Sign in',
'utf8': '✓',
'authenticity_token': authenticity_token,
'login': 'dengjn',
'password': 'd11111'}
header={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36'
} res2 =session.post("https://github.com/session",headers=header,data=data) with open("github.html","wb") as f:
f.write(res2.content)
print(login.status_code)
print(res2.status_code)

方式2:

import requests

from bs4 import BeautifulSoup

# get 请求拿登录页面 ,并且通过标签找到 token
login_url ="https://github.com/login"
res1 =requests.get(login_url)
soup = BeautifulSoup(res1.text)
token=soup.find(name="input",attrs={"name":"authenticity_token"}).get("value") # name="input" 此name表示标签名
cookies1=res1.cookies.get_dict()#拿cookie # post 的请求 去登录 ,需要带参数过去,请求页面 form表单的action 会有
'''
commit: Sign in
utf8: ✓
authenticity_token: PiH1kMaw3MUDqQ==
login: dengjiyun
password: dsgasg
''' form_data={
"commit":"Sign in",
"authenticity_token":token,
"utf8":"✓",
"login":"dengjiyun",
"password":"dsdgfg",
}
url2 ="https://github.com/session" r2 =requests.post(url2,data=form_data,cookies=cookies1)
print(r2.status_code) cookies={} # 总cookies
# 将获取登录页面请求需要的cookies1和登录后的cookies合在一起
cookies2= r2.cookies.get_dict()
cookies.update(cookies1)
cookies.update(cookies2)
r3 =requests.get( url='https://github.com/new',cookies=cookies)
with open("git.html","wb") as f:
f.write(r3.content)

2 爬虫 requests模块的更多相关文章

  1. 爬虫 requests模块的其他用法 抽屉网线程池回调爬取+保存实例,gihub登陆实例

    requests模块的其他用法 #通常我们在发送请求时都需要带上请求头,请求头是将自身伪装成浏览器的关键,常见的有用的请求头如下 Host Referer #大型网站通常都会根据该参数判断请求的来源 ...

  2. 爬虫——requests模块

    一 爬虫简介 #1.什么是互联网? 互联网是由网络设备(网线,路由器,交换机,防火墙等等)和一台台计算机连接而成,像一张网一样. #2.互联网建立的目的? 互联网的核心价值在于数据的共享/传递:数据是 ...

  3. 爬虫--requests模块高级(代理和cookie操作)

    代理和cookie操作 一.基于requests模块的cookie操作 引言:有些时候,我们在使用爬虫程序去爬取一些用户相关信息的数据(爬取张三“人人网”个人主页数据)时,如果使用之前requests ...

  4. 爬虫--requests模块学习

    requests模块 - 基于如下5点展开requests模块的学习 什么是requests模块 requests模块是python中原生的基于网络请求的模块,其主要作用是用来模拟浏览器发起请求.功能 ...

  5. Python网络爬虫-requests模块(II)

    有些时候,我们在使用爬虫程序去爬取一些用户相关信息的数据(爬取张三“人人网”个人主页数据)时,如果使用之前requests模块常规操作时,往往达不到我们想要的目的,例如: #!/usr/bin/env ...

  6. Python网络爬虫-requests模块

    requests模块 requests模块是python中原生的基于网络请求的模块,其主要作用是用来模拟浏览器发起请求.功能强大,用法简洁高效.在爬虫领域中占据着半壁江山的地位. 如何使用reques ...

  7. 爬虫requests模块 1

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

  8. 爬虫 requests 模块

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

  9. 爬虫----requests模块

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

随机推荐

  1. RPMB分区介绍【转】

    本文转载自:https://blog.csdn.net/xiezhi123456/article/details/81479793 RPMB(Replay Protected Memory Block ...

  2. Linux lvm 分区知识笔记

    盘面上可以细分出扇区(Sector)与柱面(Cylinder)两种单位,其中扇区每个为512bytes那么大. 通常所说的"硬盘分区"就是指修改磁盘分区表,它定义了"第n ...

  3. Matplotlib 知识点整理

    本文作为学习过程中对matplotlib一些常用知识点的整理,方便查找. 强烈推荐ipython 无论你工作在什么项目上,IPython都是值得推荐的.利用ipython --pylab,可以进入Py ...

  4. makefile如果没有符合的显式规则将会使用隐式规则

    举例: 当前目录下有个Makefile和jello.c文件,其中有这样的规则jello.o:%.c %.h Makefile (静态模式规则),表明的含义为:要生成的jello.o目标依赖jello. ...

  5. 永久修改VS include目录

    原文:https://blog.csdn.net/sysprogram/article/details/49214727 VS2008在选项里可以设置全局的Include目录和Lib目录, 但是VS2 ...

  6. 【问题解决:连接异常】 java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long

    问题描述: MySQL更新到8.0.11之后连接数据库时会报出错误 Your login attempt was not successful, try again.Reason: Could not ...

  7. 《操作系统_FCFS和SJF》

    先来先服务FCFS和短作业优先SJF进程调度 转自:https://blog.csdn.net/qq_34374664/article/details/73231072 一.概念介绍和案例解析 FCF ...

  8. Hive安装部署及简单测试 网页《一》

    1.首先关闭机器上之前配置的分布式Hadoop 命令: (在hadoop的安装目录中)  sbin/stop-dfs.sh              关闭: yarn   命令:  sbin/stop ...

  9. Shiro学习笔记(一)

    首先展示一下项目的结构目录 工程是用maven创建的   主要是方便管理Jar包  maven的  pom文件中所需要的jar包 <dependencies> <dependency ...

  10. JavaSE习题 第九章 输入输出流

    问答题 1.如果准备读取一个文件的内容,应该使用FileInputStream还是FileOutputStream? FileInputStream 2.FileInputStream流的read() ...