Python网络爬虫案例实战:静态网页爬取:设置超时

Python网络爬虫案例实战:静态网页爬取:设置超时

有时爬虫会遇到服务器长时间不返回,这时爬虫程序就会一直等待,造成爬虫程序没能顺利地执行。因此,可以用 Requests在 timeout参数设定的秒数结束之后停止等待响应。也就是说,如果服务器在timeout 秒内没有应答,就返回异常。

把这个秒数设置为0.001秒,看看会抛出什么异常,这是为了让大家体验timeout异常的效果而设置的值,一般会把这个值设置为20秒。

>>> requests.get('http://github.com',timeout = 0.001)

Traceback (most recent call last):
  File "D:\Python37\lib\site-packages\requests\adapters.py", line 497, in send
    chunked=chunked,
  File "D:\Python37\lib\site-packages\urllib3\connectionpool.py", line 846, in urlopen
    method, url, error=new_e, _pool=self, _stacktrace=sys.exc_info()[2]
  File "D:\Python37\lib\site-packages\urllib3\util\retry.py", line 515, in increment
    raise MaxRetryError(_pool, url, reason) from reason  # type: ignore[arg-type]
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='github.com', port=80): Max retries exceeded with url: / (Caused by ConnectTimeoutError(<urllib3.connection.HTTPConnection object at 0x0000017A29F6E048>, 'Connection to github.com timed out. (connect timeout=0.001)'))

During handling of the above exception, another exception occurred:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值