简介
#介绍:使用requests可以模拟浏览器的请求,比起之前用到的urllib,requests模块的api更加便捷(本质就是封装了urllib3) #注意:requests库发送请求将网页内容下载下来以后,并不会执行js代码,这需要我们自己分析目标站点然后发起新的request请求 #安装:pip3 install requests #各种请求方式:常用的就是requests.get()和requests.post() >>> import requests >>> r = requests.get('https://api.github.com/events') >>> r = requests.post('http://httpbin.org/post', data = {'key':'value'}) >>> r = requests.put('http://httpbin.org/put', data = {'key':'value'}) >>> r = requests.delete('http://httpbin.org/delete') >>> r = requests.head('http://httpbin.org/get') >>> r = requests.options('http://httpbin.org/get')
1、GET请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
# 1、无参数实例
import
requests
ret
=
requests.get(
'https://github.com/timeline.json'
)
print
ret.url
print
ret.text
# 2、有参数实例
import
requests
payload
=
{
'key1'
:
'value1'
,
'key2'
:
'value2'
}
ret
=
requests.get(
"http://httpbin.org/get"
, params
=
payload)
print
ret.url
print
ret.text
|
向 https://github.com/timeline.json 发送一个GET请求,将请求和响应相关均封装在 ret 对象中。
2、POST请求
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
# 1、基本POST实例
import
requests
payload
=
{
'key1'
:
'value1'
,
'key2'
:
'value2'
}
ret
=
requests.post(
"http://httpbin.org/post"
, data
=
payload)
print
ret.text
# 2、发送请求头和数据实例
import
requests
import
json
url
=
'https://api.github.com/some/endpoint'
payload
=
{
'some'
:
'data'
}
headers
=
{
'content-type'
:
'application/json'
}
ret
=
requests.post(url, data
=
json.dumps(payload), headers
=
headers)
print
ret.text
print
ret.cookies
|
向https://api.github.com/some/endpoint发送一个POST请求,将请求和相应相关的内容封装在 ret 对象中。
3、其他请求
1
2
3
4
5
6
7
8
9
10
|
requests.get(url, params
=
None
,
*
*
kwargs)
requests.post(url, data
=
None
, json
=
None
,
*
*
kwargs)
requests.put(url, data
=
None
,
*
*
kwargs)
requests.head(url,
*
*
kwargs)
requests.delete(url,
*
*
kwargs)
requests.patch(url, data
=
None
,
*
*
kwargs)
requests.options(url,
*
*
kwargs)
# 以上方法均是在此方法的基础上构建
requests.request(method, url,
*
*
kwargs)
|
requests模块已经将常用的Http请求方法为用户封装完成,用户直接调用其提供的相应方法即可
Practice
import requests
import re
'''
请求方式:get、post、put…
参数:params、headers、proxies、cookies、data
'''
rsp=requests.get("https://www.hellobi.com/")
ck=requests.utils.dict_from_cookiejar(rsp.cookies)
title=re.compile("<title>(.*?)</title>",re.S).findall(rsp.text)
hd={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.221 Safari/537.36 SE 2.X MetaSr 1.0"}
px={"http":"http://127.0.0.1:8888",
"https":"http://127.0.0.1:8888",}
rsp=requests.get("https://www.hellobi.com/",proxies=px,headers=hd,cookies=ck)
key={"wd":"韦玮",
}
rsp=requests.get("http://www.baidu.com/s",headers=hd,cookies=ck,params=key)
title=re.compile("<title>(.*?)</title>",re.S).findall(rsp.text)
postdata={"name":"测试账号",
"pass":"测试密码"}
rsp=requests.post("http://www.iqianyue.com/mypost/",data=postdata)