最新Python-requests库的学习与使用举例_python中request库学习实例

def Get():
    payload = {"lady": "killer", "key": "9"}
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko)\
    Chrome/52.0.2743.116 Safari/537.36'
    }
    req = requests.get(url=URL_GET, params=payload, headers=headers)
    print("url:", req.url)
    print("状态码:", req.status_code)
    print("cookies", req.cookies)
    print("text:", req.text)
    print("json:", req.json())
    req.close()
结果

url: http://httpbin.org/get?lady=killer&key=9
状态码: 200
cookies <RequestsCookieJar[]>
text: {
  “args”: {
    “key”: “9”,
    “lady”: “killer”
  },
  “headers”: {
    “Accept”: “*/*”,
    “Accept-Encoding”: “gzip, deflate”,
    “Host”: “httpbin.org”,
    “User-Agent”: “Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko)    Chrome/52.0.2743.116 Safari/537.36”,
    “X-Amzn-Trace-Id”: “Root=1-5f8450e4-30d63b07549e5df637b48d4d”
  },
  “origin”: “59.64.129.128”,
  “url”: “http://httpbin.org/get?lady=killer&key=9”
}

json: {‘args’: {‘key’: ‘9’, ‘lady’: ‘killer’}, ‘headers’: {‘Accept’: ‘*/*’, ‘Accept-Encoding’: ‘gzip, deflate’, ‘Host’: ‘httpbin.org’, ‘User-Agent’: ’
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko)    Chrome/52.0.2743.116 Safari/537.36’, ‘X-Amzn-Trace-Id’: ‘Roo
t=1-5f8450e4-30d63b07549e5df637b48d4d’}, ‘origin’: ‘59.64.129.128’, ‘url’: ‘http://httpbin.org/get?lady=killer&key=9’}

实际访问的url已经添加了参数,也就是说,你可以不使用params参数,而是直接在url上面添加。

状态码请查看上面的文章

text是请求的结果

json格式是比较常用的

浏览器访问

POST请求

函数
post(url, data=None, json=None, **kwargs)

url:请求的url

data:请求时的数据,字典、元组列表、字节或类似文件

json:json数据

代码
def Post():
    data = {'bupt': 'beijing university of posts and communication', 'age': '65'}
    req = requests.post(URL_POST, data=data)
    print("url:", req.url)
    print("状态码:", req.status_code)
    print("cookies", req.cookies)
    print("text:", req.text)
    print("json:", req.json())
    req.close()
结果

url: http://httpbin.org/post
状态码: 200
cookies <RequestsCookieJar[]>
text: {
  “args”: {},
  “data”: “”,
  “files”: {},
  “form”: {
    “age”: “65”,
    “bupt”: “beijing university of posts and communication”
  },
  “headers”: {
    “Accept”: “*/*”,
    “Accept-Encoding”: “gzip, deflate”,
    “Content-Length”: “57”,
    “Content-Type”: “application/x-www-form-urlencoded”,
    “Host”: “httpbin.org”,
    “User-Agent”: “python-requests/2.23.0”,
    “X-Amzn-Trace-Id”: “Root=1-5f845f63-5103e9761cd94b3b1c9905f3”
  },
  “json”: null,
  “origin”: “59.64.129.128”,
  “url”: “http://httpbin.org/post”
}

json: {‘args’: {}, ‘data’: ‘’, ‘files’: {}, ‘form’: {‘age’: ‘65’, ‘bupt’: ‘beijing university of posts and communication’}, ‘headers’: {‘Accept’: ‘*/*’, ‘Accept-Encodin
g’: ‘gzip, deflate’, ‘Content-Length’: ‘57’, ‘Content-Type’: ‘application/x-www-form-urlencoded’, ‘Host’: ‘httpbin.org’, ‘User-Agent’: ‘python-requests/2.23.0’, ‘X-Amzn
-Trace-Id’: ‘Root=1-5f845f63-5103e9761cd94b3b1c9905f3’}, ‘json’: None, ‘origin’: ‘59.64.129.128’, ‘url’: ‘http://httpbin.org/post’}

高级

有的时候我们往往需要登录才有权限发送请求,而账户信息一般会保存在Cookie中。

cookies设置

可以抓包获得cookie

也可以通过F12,在控制台输入document.cookie来获得。

浏览器查看

代码

def Get_with_cookie():
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko)\
    Chrome/52.0.2743.116 Safari/537.36'
    }
    cookies = {'BIDUPSID': 'BE00784DEDAD866ECD4C82326FD62EAB', ' PSTM': '1554688108', ' MCITY': '-%3A',
               ' ispeed_lsm': '0', ' BAIDUID': '1588105DA2B8508F2F85540F7FC96277:FG', ' H_PS_PSSID': '',
               ' BDRCVFR[NPt2Vg_wYt_]': 'mk3SLVN4HKm', ' delPer': '0', ' BD_CK_SAM': '1', ' PSINO': '2',
               ' BD_UPN': '13314752', ' sug': '3', ' sugstore': '0', ' ORIGIN': '0', ' bdime': '0',
               ' H_PS_645EC': '6c6bmTTznHXowtzIVMcI9ybyItnOQcEc5yoROOp7O7Q4a0FQWI7CHETQrdW05P4yg3zuSFV3',
               ' BA_HECTOR': '24a4800l810k25k1ur1fo8obe0j', ' BDORZ': 'FFFB88E999055A3F8A630C64834BD6D0'}
    req = requests.get(URL_COOKIE, headers=headers, cookies=cookies)
    print("url:", req.url)
    print("状态码:", req.status_code)
    print("cookies", req.cookies)
    with open('ask_baidu_requets.html', 'w',encoding='utf-8') as f:
        f.write(req.text)
    req.close()

控制台输出

url: https://www.baidu.com/s?tn=02003390_hao_pg&ie=utf-8&wd=requests
状态码: 200
cookies <RequestsCookieJar[<Cookie BAIDUID=1588105DA2B8508F2F85540F7FC96277:FG=1 for .baidu.com/>, <Cookie BDRCVFR[NPt2Vg_wYt_]=mk3SLVN4HKm for .baidu.com/>, <Cookie H_
PS_PSSID= for .baidu.com/>, <Cookie PSINO=2 for .baidu.com/>, <Cookie delPer=0 for .baidu.com/>,

生成的文件

文件浏览器查看

超时设置

timeout参数

这个时间只限制请求的时间。

代码

def Get_with_timeout():
    req = requests.get('http://github.com', timeout=0.001)
    print(req.text)

结果

全部代码

"""
--coding:utf-8--
@File: learnrequests.py
@Author:frank yu
@DateTime: 2020.10.12 17:10
@Contact: frankyu112058@gmail.com
@Description:
"""
import requests

URL_GET = "http://httpbin.org/get"
URL_POST = "http://httpbin.org/post"
URL_COOKIE = "https://www.baidu.com/s?tn=02003390_hao_pg&ie=utf-8&wd=requests"


def Get():
    payload = {"lady": "killer", "key": "9"}
    headers = {


**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**

**[需要这份系统化资料的朋友,可以点击这里获取](https://bbs.csdn.net/topics/618540462)**

**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**

  • 11
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值