Python requests库的一些常用方法

requests.get()

首先,确定url。
这里,我们定义url为bugku中的一个题目

import requests    #这个和request不一样,这是两个不同的库

url = "http://123.206.87.240:8002/qiumingshan/"

此时,我们可以使用requests的一个方法

r = request.get(url)     #相当于在网址栏输入了这个url

此时的r为一个对象。
第二,代理。

proxies = {"http":"http://127.0.0.1:8080",
           "https":"http://127.0.0.1:8080"}     #这里我们将http和https统一为本地的8080端口。

也可以修改请求头和cookies

headers = {'user-agent':'xxxxxxx', 'assd':'xxxxxxxx'}
cookies = dict('cookies_are'='xxxxxxx')

但是,相应的

r = requests.get(url, proxies=proxies, headers=headers, cookies=cookies)

此时才能成功修改请求

requests.post()

requests中的post方法与其类似,不过,我们需要一个使用post方法的网址,在这里,我依然使用了bugku中的一个题目。

url = "http://123.206.87.240:8002/post/"

我们还需要将其post传递的数据进行一个处理。

pyload = {'what':'flag'}        #因为这个题目post的参数只有一个,所以我将flag作为what变量的值

然后

r = requests.post(url, data=pyload, proxies=proxies, verify=False)

此时post就传递了参数。

关于如何查看:
我们可以

print(r.content)
print(r.status_code)  #输出响应码

requests.session()

session的作用,就在于跨请求保持set-cookies,每一次我们进行一次请求都是一次全新的请求,它们set-cookies都是不一样的,如果要保持cookies一致,我们可以使用requests.session(),这样的话,就将不同的请求变成了同一次请求。

发布了27 篇原创文章 · 获赞 1 · 访问量 820

猜你喜欢

转载自blog.csdn.net/weixin_44377940/article/details/94959150