8.23第七周
8.23第七周学习内容
导入和使用模块
try...except
try...except...else
try...except...finally
raise语句
网络爬虫的一部分
代码部分
导入和使用模块、生成一个4位的验证码
import random #导入生成随机数的模块
#number = random. randint(0, 10)
#print(number)
if name == "main":
checkcode = "" #保存验证码
for i in range(0,4):
index = random. randrange(0, 3) #生成0—2的数
if index ==1:
checkcode += chr(random. randint(97, 122)) #a-z的ASCII,加号连接字符
elif index ==2:
checkcode += chr(random. randint(65, 90)) #a-z的ASCII
else:
checkcode += str(random. randint(0, 9)) #数字
print(checkcode)
try...except
def division():
print("分苹果")
apple = int(input("苹果数:"))
children = int(input("孩子数:"))
result = int(apple/children)
remain = apple - result*children
if remain>0:
print(apple,"个苹果,平均给",children,"个小朋友,每人发",result,"个","剩下",remain,"个")
else:
print(apple,"个苹果,平均给",children,"个小朋友,每人发",result,"个")
if name == "main":
try:
division()
except ZeroDivisionError:
print("出错了,孩子数不能为0")
except ValueError:
print("出错了,不能为小数")
else:
print("Devision completed!")
try...except
def division():
print("分苹果")
apple = int(input("苹果数:"))
children = int(input("孩子数:"))
result = int(apple/children)
remain = apple - result*children
if remain>0:
print(apple,"个苹果,平均给",children,"个小朋友,每人发",result,"个","剩下",remain,"个")
else:
print(apple,"个苹果,平均给",children,"个小朋友,每人发",result,"个")
if name == "main":
try:
division()
except ZeroDivisionError:
print("出错了,孩子数不能为0")
except ValueError:
print("出错了,不能为小数")
finally:#(总是执行)
print("Division has done once")
raise语句
def division():
print("分苹果")
apple = int(input("苹果数:"))
children = int(input("孩子数:"))
if apple < children:
pass#raise ValueError("Too less apples!") #下面会被 except ValueError: 捕获到
result = int(apple/children)
remain = apple - result*children
if remain>0:
print(apple,"个苹果,平均给",children,"个小朋友,每人发",result,"个","剩下",remain,"个")
else:
print(apple,"个苹果,平均给",children,"个小朋友,每人发",result,"个")
if name == "main":
try:
division()
except ZeroDivisionError:
print("出错了,孩子数不能为0")
except ValueError:
if apple < children:
print("出错了,不够分")
else:
print("出错了,不能为小数")
finally:#(总是执行)
print("Division has done once")
网络爬虫1
import urllib.request #导入网络请求模块
response = urllib.request.urlopen('http://www.fishc.com/')
print(response.read().decode("utf-8"))
网络爬虫2
import urllib.request #导入网络请求模块
response = urllib.request.urlopen('http://placekitten.com/g/500/600')
cat_img = response.read()
with open('cat_500_600.jpg','wb') as f:
f.write(cat_img)
网络爬虫3
import urllib.request
import urllib.parse
import json
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
data={}
data['type'] = 'AUTO'
data['i'] = 'i love fish!'
data['doctype'] = 'json'
data['Version'] = '1.6'
data['keyfrom'] = 'fanyi.web'
data['ue'] = 'utf-8'
data['typoResult'] = 'true'
data = urllib.parse.urlencode(data).encode('utf-8')
response = urllib.request.urlopen(url,data)
html = response.read().decode('utf-8')
print(html)