异常值的处理:try & 爬虫初识
---------------------------异常值处理-------------------------
异常值处理:防止程序奔溃
-
#常见的用法 try: val = input('请输入数字:') num = int(val) except Exception as e: #Exception固定格式:捕获所有类型的异常 print('操作异常') #如果程序报错,执行如下内容 # 也可用于函数 def func(a): try: a.strip() except Exception as e: print('处理失败') return 123 v = func([11,22,33]) print(v)
#捕获单个异常
try:
print("----text-----1----")
f = open("123.txt","r")
print("-----test------2---")
print(num)
except(NameError,IOError)as result:#IOError:输入输出错误,如果两个错误都有的话,并列加括号。
print("产生错误了")
print(result)#产生错误的提示信息
异常练习题
import time
try:
f = open("123.tet","r")
try:
while True:
content = f.readline()
if len(content) == 0:
break
time.sleep(2)
print(content)
finally:#不论有没有异常finally一定会被执行,保证文件异常与否都会被关闭
f.close()
print("文件关闭")
except Exception as result:
print("发生异常")
爬虫的应用
import requests
def func1(url_list):
result = []
for url in url_list:
try:
response = requests.get(url)
result.append(response.text)
except Exception as e:
pass
return result
func1(['http://www.baidu.com','http://www.google.com'])
记录学习的点点滴滴