Requests 库的两个重要的对象:(Request , Response)

Response对象的属性:

  1. import requests
  2. r =requests.get('http://www.bilibili.com') response 对象 <Response [200]>
  3.  
  4. print(r.status_code) # 200状态码-----404错误
  5. print(r.headers) # 请求码
  6. print(r.text) # 字符串形式
  7. print(r.encoding) # 网页的编码方式-根据headers猜测
  8. print(r.apparent_encoding) # 根据内容响应的编码方式(r.encoding=r.apparent_encoding)
  9. print(r.content) # 二进制形式
  10.  
  11.  
  1.  

  requests 库的7个重要的方法:

  1. =============== requests 库的7个重要的方法 ==============
  2. ---1 requests.request(method,url,**kwargs)
  1. ---2 requests.get(url,params=None,**kwargs)
  1. ---3 requests.head(url,**kwargs)
  1. ---4 requests.post(url,data=None,json=None,**kwargs)
  1. ---5 requests.put(url,data=None,**kwargs)
  1. ---6 requests.patch(url,data=None,**kwargs)
  1. ---7 requests.delete(url,**kwargs)

Requests 请求的通用代码框架:

  1. === 通用框架 ===
  2. import requests
  3.  
  4. def getHTMLText(url):
  5. try:
  6. r=requests.get(url,timeout=30) # <Response [200]>
  7. r.raise_for_status() # 如果状态码不是200,引发HTTPError异常
  8. r.encoding=r.apparent_encoding
  9. return r.text
  10. except:
  11. return 'Error!'
  12. if __name__=='__main__':
  13. url='http://www.baidu.com'
  14. print(getHTMLText(url))

 伪装浏览器请求:

  1. 常用请求头:
  2.  
  3. Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)
  4. #opera浏览器
  5. Opera/9.80 (X11; Linux i686; U; ru) Presto/2.8.131 Version/11.11
  6. #chrome浏览器
  7. Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.2 (KHTML, like Gecko) Chrome/22.0.1216.0 Safari/537.2

  8. #firefox浏览器
  9. Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1

  10. #safri浏览器
  11. Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5355d Safari/8536.25
  1. 例子 1 跟换请求头
  2.  
  3. 亚马逊通会过来源审查 阻止访问-----需要更改请求头
  4. import requests
  5. url='https://www.amazon.cn/dp/B07473FZXY?_encoding=UTF8&ref_=pc_cxrd_658390051_recTab_335775071_t_3&pf_rd_p=7e00fee6-4e12-48f0-b4af-b99068b52067&pf_rd_s=merchandised-search-4&pf_rd_t=101&pf_rd_i=658390051&pf_rd_m=A1AJ19PSB66TGU&pf_rd_r=1SV7P98M8XX2E5N2PBW5&pf_rd_r=1SV7P98M8XX2E5N2PBW5&pf_rd_p=7e00fee6-4e12-48f0-b4af-b99068b52067'
  6. try:
  7. header={'User-Agent':'Mozilla/5.0'} # 'Mozilla/5.0'---浏览器身份标识
  8. r=requests.get(url,headers=header)
  9. r.raise_for_status()
  10. r.encoding=r.apparent_encoding
  11. print(r.text[1000:2000])
  12. except Exception:
  13. print('Error!')
  14.  
  15. print(r.request.url) #当前请求的网页 https://www.amazon.cn/%E5%9B%BE%E4%B9%A6/dp/B07473FZXY
  16. print(r.request.headers) # 当前的请求头 {'User-Agent': 'python-requests/2.18.2', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}
  1. 例子 2 关键字搜索--百度
  2. import requests
  3. keyword={'wd':'Python'}
  4. url='https://www.baidu.com/s'
  5. try:
  6. r=requests.get(url,params=keyword)
  7. r.raise_for_status()
  8. r.encoding=r.apparent_encoding
  9. print(r.request.url)
  10. # print(len(r.text))
  11. print(r.text)
  12. except Exception:
  13. print('Error!')

 

  1. 例子 3 图片 爬取 保存
  2.  
  3. import requests
  4. import os
  5. url='http://pic1.16pic.com/00/14/32/16pic_1432548_b.jpg'
  6. root=r'C:\Users\Administrator\Desktop'
  7. path=root+'\\'+url.split('/')[-1]
  8. try:
  9. if not os.path.exists(root): # 根目录是否存在
  10. os.mkdir(root)
  11. elif not os.path.exists(path): # 文件是否存在
  12. r=requests.get(url) # <Response [200]>
  13. # print(r.status_code)
  14. # print(r.content) # 二进制
  15. with open(path,'wb') as f:
  16. f.write( r.content ) # 二进制写入
  17. print('文件操作成功!')
  18. else:
  19. print('文件已经存在!')
  20. except:
  21. print('Error!')
  1. 例子 5 ip 地址的归属地查询----ip138.com
  2. import requests
  3. url='http://www.ip138.com/ips138.asp?ip='
  4. ip='202.204.80.112'
  5. url=url+ip
  6. try:
  7. r=requests.get(url)
  8. # print(r) # ===回应==== <Response [200]>
  9. # print(r.request.url) # ===请求==== http://www.ip138.com/ips138.asp?ip=202.204.80.112
  10. r.raise_for_status()
  11. r.encoding=r.apparent_encoding
  12. print(r.text[-500:])
  13. except:
  14. print('Error!')

Requests 库的更多相关文章

  1. Python爬虫小白入门(二)requests库

    一.前言 为什么要先说Requests库呢,因为这是个功能很强大的网络请求库,可以实现跟浏览器一样发送各种HTTP请求来获取网站的数据.网络上的模块.库.包指的都是同一种东西,所以后文中可能会在不同地 ...

  2. Requests库上传文件时UnicodeDecodeError: 'ascii' codec can't decode byte错误解析

    在使用Request上传文件的时候碰到如下错误提示: 2013-12-20 20:51:09,235 __main__ ERROR 'ascii' codec can't decode byte 0x ...

  3. Requests库的几种请求 - 通过API操作Github

    本文内容来源:https://www.dataquest.io/mission/117/working-with-apis 本文的数据来源:https://en.wikipedia.org/wiki/ ...

  4. python脚本实例002- 利用requests库实现应用登录

    #! /usr/bin/python # coding:utf-8 #导入requests库 import requests #获取会话 s = requests.session() #创建登录数据 ...

  5. 大概看了一天python request源码。写下python requests库发送 get,post请求大概过程。

    python requests库发送请求时,比如get请求,大概过程. 一.发起get请求过程:调用requests.get(url,**kwargs)-->request('get', url ...

  6. python WEB接口自动化测试之requests库详解

    由于web接口自动化测试需要用到python的第三方库--requests库,运用requests库可以模拟发送http请求,再结合unittest测试框架,就能完成web接口自动化测试. 所以笔者今 ...

  7. python爬虫从入门到放弃(四)之 Requests库的基本使用

    什么是Requests Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库如果你看过上篇文章关于urllib库的使用,你会发现,其 ...

  8. (转)Python爬虫利器一之Requests库的用法

    官方文档 以下内容大多来自于官方文档,本文进行了一些修改和总结.要了解更多可以参考 官方文档 安装 利用 pip 安装 $ pip install requests 或者利用 easy_install ...

  9. python requests库学习笔记(上)

    尊重博客园原创精神,请勿转载! requests库官方使用手册地址:http://www.python-requests.org/en/master/:中文使用手册地址:http://cn.pytho ...

  10. 使用Python的requests库进行接口测试——session对象的妙用

    from:http://blog.csdn.net/liuchunming033/article/details/48131051 在进行接口测试的时候,我们会调用多个接口发出多个请求,在这些请求中有 ...

随机推荐

  1. jquery 字符串转为json

    使用ajax从服务器拿到的数据,jquery总是认为是字符串,无法直接使用,可以通过下面代码转换: $.get("服务器路径", function(data) { data = e ...

  2. 谷歌机器学习速成课程---2深入了解机器学习(Descending into ML)

    1.线性回归 人们早就知晓,相比凉爽的天气,蟋蟀在较为炎热的天气里鸣叫更为频繁.数十年来,专业和业余昆虫学者已将每分钟的鸣叫声和温度方面的数据编入目录.Ruth 阿姨将她喜爱的蟋蟀数据库作为生日礼物送 ...

  3. yii2-lock-form 也许这就是你想要的,阻止表单多次提交

    是不是被用户的行为所困扰? 一个表单用户点击提交按钮了N次,这也导致了数据提交了N次. 为了此受到了测试的欺辱,受到了老板的批评? 不用怕,它就是来拯救你的. 第一步:打开命令行,敲入 compose ...

  4. facebook开源了他们的分布式大数据DB

    https://github.com/facebook/presto facebook 3天前开源了他们的 分布式大数据DB Distributed SQL query engine for big ...

  5. Linux权限管理 chattr命令、lsattr命令、sudo命令

    chattr命令 chattr命令用来修改文件系统的权限属性 chatrr 只有 root 用户可以使用,用来修改文件系统的权限属性,建立凌驾于 rwx 基础权限之上的授权. chatrr 命令格式如 ...

  6. 关于dispatch_semaphore的使用

    dispatch_semaphore是GCD用来同步的一种方式,与他相关的共有三个函数,分别是 dispatch_semaphore_create,dispatch_semaphore_signal, ...

  7. python + Streaming框架的MR实践与优化

    Streaming是Hadoop提供的一个可以使用其他编程语言来进行MR编程的API,它使用Unix标准输入输出作为Hadoop和其他编程语言的开发接口,非常轻便.而开发者可以选择自己擅长的编程语言, ...

  8. jQuery横向图片手风琴

    在线演示 本地下载

  9. debian内核代码执行流程(三)

    接续<debian内核代码执行流程(二)>未完成部分 下面这行输出信息是启动udevd进程产生的输出信息: [ ]: starting version 175是udevd的版本号. 根据& ...

  10. 山东省第六届ACM省赛 H---Square Number 【思考】

    题目描述 In mathematics, a square number is an integer that is the square of an integer. In other words, ...