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. 碎碎念android eMMC【转】

    本文转载自:https://blog.csdn.net/Fybon/article/details/44242549 一./dev/blockroot@:/dev/block #ls bootdevi ...

  2. YII框架的使用

    YII框架的使用 spit: 吐痰,吐口水, 过去式: spat spat: 本身也可以作为一个单词, 意思是: "小打小闹""小的吵闹""小争吵&q ...

  3. (转)Spring Boot(二) & lombok

    (二期)5.springboot框架集成与lombok [课程五]springb...mbok.xmind0.1MB [课程五预习]spr...mbok.xmind0.1MB springboot的版 ...

  4. IE8下面parseInt('08')、parseInt('09')会转成0

    例子: <html> <body> <script type="text/javascript"> for(var i=1;i<=20;i ...

  5. python爬虫训练——正则表达式+BeautifulSoup爬图片

    这次练习爬 传送门 这贴吧里的美食图片. 如果通过img标签和class属性的话,用BeautifulSoup能很简单的解决,但是这次用一下正则表达式,我这也是参考了该博主的博文:传送门 所有图片的s ...

  6. java复制文件夹中的所有文件和文件夹到另一个文件夹中

    1.复制文件夹 public static void copyDir(String oldPath, String newPath) throws IOException { File file = ...

  7. SQLServer代理新建或者编辑作业报错

    SQLServer代理新建或者编辑作业的时候报错如下 错误信息: 标题: Microsoft SQL Server Management Studio------------------------- ...

  8. 【Django】Django-REST-Framework

    [创建简单的API] 1. cmd.exe >django-admin startproject django_rest>cd django_rest\django_rest>pyt ...

  9. Webpack+React项目入门——入门及配置Webpack

    一.入门Webpack 参考文章:<入门Webpack,看这篇就够了> 耐心看完这篇非常有帮助 二.React+Webpack环境配置 参考文章:<webpack+react项目初体 ...

  10. _rate_charaters

    该表可以控制特定玩家的掉率 guid 玩家角色guid,characters表中guid rate 掉落倍率,比如1.1,则该玩家普通掉率(groupid = 0时)提高1.1倍