美文网首页
Python之requests的简易使用

Python之requests的简易使用

作者: 天命_风流 | 来源:发表于2020-02-27 22:07 被阅读0次

参考:https://www.cnblogs.com/wupeiqi/articles/6283017.html

请求方法:

    requests.get()
    requests.post() 
    requests.put ()
    requests.delete() 

参数

  • url :设置访问的url
requests.get('https://www.baidu.com')
  • headers:用于伪造请求头
requests.get(url = 'http://www.ip138.com/', headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36'})
  • cookies:用于传递cookies
requests.get(url = 'xxxx.com' , cookies = { 'k1':'v1' })
  • params:在get方法中用于提交数据
requests.get(url = 'xxxx.com', params = { 'k1' : 'v1' })
  • data:在post方法中用于提交数据
requests.post(..., data={'k1':'v1'} )
  • json:传送json请求体
requests.post(..., json={'user':'alex','pwd':'123'} )
  • proxies:使用代理
        # 无验证
            proxie_dict = {
                "http": "61.172.249.96:80",
                "https": "http://61.185.219.126:3128",
            }
            ret = requests.get("https://www.proxy360.cn/Proxy", proxies=proxie_dict)
            
        
        # 验证代理
            from requests.auth import HTTPProxyAuth
            
            proxyDict = {
                'http': '77.75.105.165',
                'https': '77.75.106.165'
            }
            auth = HTTPProxyAuth('用户名', '密码')
            
            r = requests.get("http://www.google.com",data={'xxx':'ffff'} proxies=proxyDict, auth=auth)
            print(r.text)
  • files:上传文件
            file_dict = {
                'f1': open('xxxx.log', 'rb')
            }
            requests.request(
                method='POST',
                url='http://127.0.0.1:8000/test/',
                files=file_dict
            )
  • timeout:设置超时时间
ret = requests.get('http://google.com/', timeout=1)     #设置连接超时时间
ret = requests.get('http://google.com/', timeout=(3,1) )      #设置连接和返回数据的超时时间
  • allow_redirects:是否允许重定向
ret = requests.get('http://127.0.0.1:8000/test/', allow_redirects=False)
  • stream:大型文件下载
        from contextlib import closing
        with closing(requests.get('http://httpbin.org/get', stream=True)) as r1:
        # 在此处理响应。
        for i in r1.iter_content():
            print(i)

相关文章

网友评论

      本文标题:Python之requests的简易使用

      本文链接:https://www.haomeiwen.com/subject/qksfhhtx.html