惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Google DeepMind News
Google DeepMind News
WordPress大学
WordPress大学
S
SegmentFault 最新的问题
小众软件
小众软件
爱范儿
爱范儿
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
量子位
博客园_首页
T
Tailwind CSS Blog
The Cloudflare Blog
J
Java Code Geeks
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
U
Unit 42
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
人人都是产品经理
人人都是产品经理
N
Netflix TechBlog - Medium
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
腾讯CDC
P
Proofpoint News Feed
aimingoo的专栏
aimingoo的专栏
Recent Announcements
Recent Announcements
T
The Blog of Author Tim Ferriss
D
Docker
Microsoft Azure Blog
Microsoft Azure Blog

老董笔记

尚硅谷机构在哪?尚硅谷培训怎么样?靠谱吗-互联网IT百科 韩顺平介绍,传智讲师,开办泰牛,入尚硅谷等一系列-互联网IT百科 pandas多重索引标准样式(写入excel有空行)-互联网IT百科 cannot join with no overlapping index names-互联网IT百科 pandas多列变多行(即宽表变长表)melt和stack函数-互联网IT百科 pandas多行转多列(长表变宽表)pivot和unstack-互联网IT百科 Index contains duplicate entries, cannot reshape完美解决-互联网IT百科 single positional indexer is out-of-bounds-互联网IT百科 Can only compare identically-labeled Series objects-互联网IT百科 pandas transform用法详解(多个案例)-互联网IT百科 python四舍五入精确实现-互联网IT百科 pandas的groupby使用apply分组排序-互联网IT百科 index 0 is out of bounds for axis 0 with size 0-互联网IT百科 pandas分组过滤filter函数-互联网IT百科 联想Win10系统如何禁用触摸屏关闭触摸-互联网IT百科 groupby分组计算transform转换返回相同长度序列-互联网IT百科 brooks seo教程python教程,brooks seo教程网盘,布鲁seo资源-互联网IT百科 电脑右键文件夹一直转圈电卡死怎么回事-互联网IT百科 施琪嘉的心理成长课(荐)-互联网IT百科 百度SEO公司_SEO推广公司哪家好_SEO外包服务如何选-老董笔记 groupby后agg同1列用多个聚合函数、不同列用不同函数、自定义函数-互联网IT百科 pandas的groupby单列多列分组聚合运算-互联网IT百科 DataFrameGroupBy对象及分组个数、分组大小、组名索引、组数据详解-互联网IT百科 pandas中groupby之Grouper and axis must be same length-互联网IT百科 pandas中groupby的分组原理-互联网IT百科 pandas的groupby的使用详解大全-互联网IT百科 openpyxl单元格自动换行强制换行Alignment(wrapText=True)-互联网IT百科 python教程全套(可就业)-互联网IT百科 联想win10系统CPU显示100%,电脑呼呼响怎么回事-互联网IT百科 如何自制CPU,CPU原理是怎么样的?-互联网IT百科
requests请求超时处理与异常总结-互联网IT百科
2019-07-18 · via 老董笔记

  有时候在上网的时候打开1个网页非常卡,浏览器要转半天才转出来,这种情况在用代码请求网页的时候也会遇到。所以requests模块提供了1个timeout参数来设定请求时间(秒数),超出秒数以后就会抛出requests.exceptions.Timeout异常。

  PS:正常所有的爬虫代码都应该使用timeout参数。如果不使用,可能会出现某个请求一直在等服务器的响应而导致整个程序阻塞,程序看起来卡着不动了!

# -*- coding: utf-8 -*-
url = 'https://github.com'
try:
  requests.get('https://github.com',timeout=0.0001)
except requests.exceptions.Timeout  as e:
  print(e)
HTTPSConnectionPool(host='github.com', port=443): Max retries exceeded with url: / (Caused by ConnectTimeoutError(, 'Connection to github.com timed out. (connect timeout=0.0001)'))

  timeout仅对连接过程有效,与响应体的下载无关。timeout并不是整个下载响应的时间限制,而是如果服务器在 timeout 秒内没有应答,将会引发一个异常(更精确地说,是在 timeout 秒内没有从基础套接字上接收到任何字节的数据时)If no timeout is specified explicitly, requests do not time out.

  上网过程可能出现各种各样的问题,比如网站服务器挂了,域名已经过期了无法访问,国外的敏感网站国内不能访问,网络断线了等等,所以访问网页过程中遇到的异常不只有超时1种,下面简单介绍下。

  requests异常介绍

  ConnectionError 异常:遇到网络问题(如:DNS 查询失败、拒绝连接等时,Requests会抛出。

# -*- coding: utf-8 -*-
try:
  requests.get('https://google.com',timeout=5)
except requests.exceptions.ConnectionError  as e:
  print(e)
('Connection aborted.', ConnectionResetError(10054, '远程主机强迫关闭了一个现有的连接。', None, 10054,
None))

  ConnectTimeoutError异常:若请求超时,则抛出。

# -*- coding: utf-8 -*-
try:
  requests.get('https://baidu.com',timeout=0.00001)
except requests.exceptions.Timeout  as e:
  print(e)
HTTPSConnectionPool(host='baidu.com', port=443): Max retries exceeded with url: / (Caused by ConnectTimeoutError(, 'Connection to baidu.com timed out. (connect timeout=1e-05)'))

  TooManyRedirects异常:若请求超过了设定的最大重定向次数,则会抛出。(requests设置最大重定向测试很多方式并没有生效)

# -*- coding: utf-8 -*-
def get_html(url,retry=1):
    try:
        r = requests.get(url=url,headers=my_header, timeout=5)
    except requests.exceptions.RequestException as e:
        print(e)
        if retry > 0:
            get_html(url, retry - 1)
    else:
        html = r.text
        return html

  所有Requests显式抛出的异常都继承自requests.exceptions.RequestException,可以直接用这个基类来捕获。

# -*- coding: utf-8 -*-
try:
  requests.get('https://360.com',timeout=0.00001)
except requests.exceptions.RequestException  as e:
  print(e)
HTTPSConnectionPool(host='360.com', port=443): Max retries exceeded with url: / (Caused by ConnectTimeoutError(, 'Connection to 360.com timed out. (connect timeout=1e-05)'))

  也可以用python内置的Exception类来捕获。

# -*- coding: utf-8 -*-
try:
  requests.get("https://360.com",timeout=0.00001)
except  Exception  as e:
  print(e)
HTTPSConnectionPool(host='360.com', port=443): Max retries exceeded with url: / (Caused by ConnectTimeoutError(, 'Connection to 360.com timed out. (connect timeout=1e-05)'))

很赞哦!

python编程网提示:转载请注明来源www.python66.com。
有宝贵意见可添加站长微信(底部),获取技术资料请到公众号(底部)。同行交流请加群 python学习会