requests是python实现的简单易用的HTTP库,使用起来比urllib简洁很多

因为是第三方库,所以使用前需要cmd安装

pip install requests

安装完成后import一下,正常则说明可以开始使用了。

基本用法:

requests.get()用于请求目标网站,类型是一个HTTPresponse类型

import requestsresponse = requests.get('http://www.baidu.com')
print(response.status_code)  # 打印状态码
print(response.url)          # 打印请求url
print(response.headers)      # 打印头信息
print(response.cookies)      # 打印cookie信息
print(response.text)  #以文本形式打印网页源码
print(response.content) #以字节流形式打印

运行结果:

状态码:200

url:www.baidu.com

headers信息

各种请求方式:

import requestsrequests.get('http://httpbin.org/get')
requests.post('http://httpbin.org/post')
requests.put('http://httpbin.org/put')
requests.delete('http://httpbin.org/delete')
requests.head('http://httpbin.org/get')
requests.options('http://httpbin.org/get')

基本的get请求

import requestsresponse = requests.get('http://httpbin.org/get')
print(response.text)

结果

带参数的GET请求:

第一种直接将参数放在url内

import requestsresponse = requests.get(http://httpbin.org/get?name=gemey&age=22)
print(response.text)

结果

另一种先将参数填写在dict中,发起请求时params参数指定为dict

import requestsdata = {'name': 'tom','age': 20
}response = requests.get('http://httpbin.org/get', params=data)
print(response.text)

结果同上

解析json

import requestsresponse = requests.get('http://httpbin.org/get')
print(response.text)
print(response.json())  #response.json()方法同json.loads(response.text)
print(type(response.json()))

结果

简单保存一个二进制文件

二进制内容为response.content

import requestsresponse = requests.get('http://img.ivsky.com/img/tupian/pre/201708/30/kekeersitao-002.jpg')
b = response.content
with open('F://fengjing.jpg','wb') as f:f.write(b)

为你的请求添加头信息

import requests
heads = {}
heads['User-Agent'] = 'Mozilla/5.0 ' \'(Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 ' \'(KHTML, like Gecko) Version/5.1 Safari/534.50'
 response = requests.get('http://www.baidu.com',headers=headers)

使用代理

同添加headers方法,代理参数也要是一个dict

这里使用requests库爬取了IP代理网站的IP与端口和类型

因为是免费的,使用的代理地址很快就失效了。

import requests
import redef get_html(url):proxy = {'http': '120.25.253.234:812','https' '163.125.222.244:8123'}heads = {}heads['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'req = requests.get(url, headers=heads,proxies=proxy)html = req.textreturn htmldef get_ipport(html):regex = r'<td data-title="IP">(.+)</td>'iplist = re.findall(regex, html)regex2 = '<td data-title="PORT">(.+)</td>'portlist = re.findall(regex2, html)regex3 = r'<td data-title="类型">(.+)</td>'typelist = re.findall(regex3, html)sumray = []for i in iplist:for p in portlist:for t in typelist:passpassa = t+','+i + ':' + psumray.append(a)print('高匿代理')print(sumray)if __name__ == '__main__':url = 'http://www.kuaidaili.com/free/'get_ipport(get_html(url))

结果:

基本POST请求:

import requestsdata = {'name':'tom','age':'22'}response = requests.post('http://httpbin.org/post', data=data)

获取cookie

#获取cookie
import requestsresponse = requests.get('http://www.baidu.com')
print(response.cookies)
print(type(response.cookies))
for k,v in response.cookies.items():print(k+':'+v)

结果:

会话维持

import requestssession = requests.Session()
session.get('http://httpbin.org/cookies/set/number/12345')
response = session.get('http://httpbin.org/cookies')
print(response.text)

结果:

证书验证设置

import requests
from requests.packages import urllib3urllib3.disable_warnings()  #从urllib3中消除警告
response = requests.get('https://www.12306.cn',verify=False)  #证书验证设为FALSE
print(response.status_code)打印结果:200

超时异常捕获

import requests
from requests.exceptions import ReadTimeouttry:res = requests.get('http://httpbin.org', timeout=0.1)print(res.status_code)
except ReadTimeout:print(timeout)

异常处理

在你不确定会发生什么错误时,尽量使用try...except来捕获异常

所有的requests exception:

Exceptions

import requests
from requests.exceptions import ReadTimeout,HTTPError,RequestExceptiontry:response = requests.get('http://www.baidu.com',timeout=0.5)print(response.status_code)
except ReadTimeout:print('timeout')
except HTTPError:print('httperror')
except RequestException:print('reqerror')

来源:https://www.cnblogs.com/mzc1997/p/7813801.html

python爬虫---requests库的用法相关推荐

  1. 【python】python爬虫requests库详解

    1.安装:pip install requests 简介:Requests是一个优雅而简单的Python HTTP库,与之前的urllibPython的标准库相比,Requests的使用方式非常的简单 ...

  2. 已解决(Python爬虫requests库报错 请求异常SSL错误,证书认证失败问题)requests.exceptions.SSLError: HTTPSConnectionPool

    成功解决(Python爬虫requests库报错 请求异常,SSL错误,证书认证失败问题)requests.exceptions.SSLError: HTTPSConnectionPool(host= ...

  3. Python爬虫——Requests 库基本使用

    文章目录 Python爬虫--Requests 库基本使用 1.Requests简介和下载 2.Requests 库基本使用 Python爬虫--Requests 库基本使用 1.Requests简介 ...

  4. Python 的 requests 库的用法

    Python爬虫利器一之Requests库的用法:http://cuiqingcai.com/2556.html Python利用Requests库写爬虫(一):http://www.jianshu. ...

  5. python爬虫requests库_python爬虫使用Requests库 - pytorch中文网

    在入门教程中我们介绍了urllib库和urllib2的用法,同时我们了解一些爬虫的基础以及对爬虫有了基本的了解.其实在我们生产环境中,使用Request库更加方便与实用,同时我们这需要短短的几行代码就 ...

  6. python爬虫requests库_Python爬虫(三)Requests库

    什么是Requests Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库.与urllib相比,Requests更加方便,可以节约 ...

  7. 【Python成长之路】Python爬虫 --requests库爬取网站乱码(\xe4\xb8\xb0\xe5\xa)的解决方法【华为云分享】

    [写在前面] 在用requests库对自己的CSDN个人博客(https://blog.csdn.net/yuzipeng)进行爬取时,发现乱码报错(\xe4\xb8\xb0\xe5\xaf\x8c\ ...

  8. python爬虫requests库_python爬虫基础教程:requests库(二)代码实例

    get请求 简单使用 import requests ''' 想要学习Python?Python学习交流群:973783996满足你的需求,资料都已经上传群文件,可以自行下载! ''' respons ...

  9. 【Python成长之路】Python爬虫 --requests库爬取网站乱码(\xe4\xb8\xb0\xe5\xaf\x8c\xe7\x9)的解决方法

    [写在前面] 在用requests库对自己的CSDN个人博客(https://blog.csdn.net/yuzipeng)进行爬取时,发现乱码报错(\xe4\xb8\xb0\xe5\xaf\x8c\ ...

最新文章

  1. 洛谷 P1008 三连击 Label:水
  2. WM8962 HPOUT 信号强度 时间周期
  3. 关于Ajax 错误:'sys'未定义解决方法.
  4. openssl+poly1305+sm4实现
  5. web基础html元素制作web
  6. C++不区分大小写比较string类似CString.compareNoCase
  7. mongodb php 扩展 linux,CentOS Linux 安装PHP的MongoDB扩展
  8. Maven的pom报错的解决方法
  9. poj 2528 Mayor's posters(线段树+离散化)
  10. 人件第二版(中文版)pdf
  11. uni-app:uni.navigateTo 封装页面跳转传参
  12. iOS-详解没有dSYM文件 如何解析iOS崩溃日志
  13. 鄂尔多斯固体废物智慧化管理平台设备和功能概况
  14. 如何发一条九宫格图片的朋友圈
  15. 虚拟存储页面置换算法c语言,虚拟存储器管理页面置换算法模拟实验.doc
  16. 《谷粒商城》-项目简介以及环境搭建
  17. 2017工业互联网峰会 | 天拓四方助力中国工业生产、制造业转型升级
  18. Your hostname, xxx resolves to a loopback address: 127.0.1.1; using x.x.x.x instead(on interface xx)
  19. 2021-05-01Java面试知识点
  20. hive正则表达式regexp_extract

热门文章

  1. C++对C的加强之变量检测增强
  2. python求两数最大公因数_『用python求俩个数的最大公约数和最小公倍数』
  3. Pytorch实现基本循环神经网络RNN (3)
  4. Spark Streaming从Kafka中拉取数据,并且使用过“窗口函数”统计一些流量信息
  5. 13_Android的生命周期
  6. Nginx+Tomcat负载均衡配置
  7. Oracle过滤与排序
  8. Excel多因素不重复方差分析
  9. typescript 接口 interface
  10. source tree常用功能