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. 12.27 cf div3 解题报告

    12.27 cf div3 解题报告 wxy.wxy,带上分拉,全场做了个无脑小白 比赛场地 A: T1,跟着模拟就好了 B: sort一遍之后 去除的数一定是a[1]或者a[n] 比较去除谁小就输出 ...

  2. P3605 [USACO17JAN]Promotion Counting晋升者计数

    思路 线段树合并的板子.. 和子节点合并之后在值域线段树上查询即可 代码 #include <cstdio> #include <algorithm> #include < ...

  3. P5057 [CQOI2006]简单题(线段树)

    果然简单题,5分钟紫题++ 代码 #include <cstdio> #include <algorithm> #include <cstring> using n ...

  4. parent获取子元素以及自身元素

    innerHTML 设置或获取位于对象起始和结束标签内的 HTML outerHTML 设置或获取对象及其内容的 HTML 形式 innerText 设置或获取位于对象起始和结束标签内的文本 oute ...

  5. Writing device drivers in Linux: A brief tutorial

    “Do you pine for the nice days of Minix-1.1, when men were men and wrote their own device drivers?”  ...

  6. javaScript 内置对象-Array数组

    Array 对象方法 方法 描述 concat() 连接两个或更多的数组,并返回结果. join() 把数组的所有元素放入一个字符串.元素通过指定的分隔符进行分隔. pop() 删除并返回数组的最后一 ...

  7. android获取屏幕宽度和高度

    1. WindowManager wm = (WindowManager) getContext() .getSystemService(Context.WINDOW_SERVICE); int wi ...

  8. _itemmod_refresh

    -- 随机FM刷新设置-- 小技巧:很多服所说的装备鉴定效果可以通过这个实现,也可以对物品重新生成新的附魔--详细解说一下鉴定系统如何实现--1首先在_itemmod_enchant_groups中添 ...

  9. 关于JAVA中包装类的是什么类型传递这个问题的笔记

    背景知识: 如果参数类型是原始类型,那么传过来的就是这个参数的一个副本,也就是这个原始参数的值.如果在函数中改变了副本的值不会改变原始的值. 如果参数类型是引用类型,那么传过来的就是这个参数的引用,这 ...

  10. 求文件的hash值(基于SHA3的Hash)

    import hashlib import tkinter from tkinter import filedialog import pyperclip def fileHash(fileName) ...