python爬虫——requests获取html(带异常处理)

import requests
from bs4 import BeautifulSoup
url='www.google.com'
print('url=',url)
try:
	response = requests.get(url,timeout=(3,7)) #返回Response对象
	#print(response.status_code)这句话似乎只能显示正常状态码200,异常状态码都不能显示,待查
	response.raise_for_status() #若状态码不是200,抛出HTTPError异常
	response.encoding = response.apparent_encoding  #保证页面编码正确
except requests.exceptions.ConnectTimeout:
	print( '超时!')
except requests.exceptions.ConnectionError:
	print('无效地址!')
html=response.text
html = BeautifulSoup(html, 'lxml')
with open("1.html", 'w', encoding="utf-8") as f:#存到html文件
		f.write(html.prettify())

在这里插入图片描述

在这里插入图片描述


详细在工程里操作,先不适用try,直接显示异常,
在这里插入图片描述
查看到异常,再在except后面输入。
如果不要只要判断正确或异常(不考虑异常类型),将try部分改为如下:

try:
	response = requests.get(url,timeout=(3,7)) #返回Response对象
	#print(response.status_code)这句话似乎只能显示正常状态码200,异常状态码都不能显示,待查
	response.raise_for_status() #若状态码不是200,抛出HTTPError异常
	response.encoding = response.apparent_encoding  #保证页面编码正确
except:
	print('异常!')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值