python之爬虫的入门02------爬取图片、异常处理

一、爬取一张图片

import urllib.request

req = 'http://placekitten.com/400/400'   # url地址
response = urllib.request.urlopen(req)   #用文件形式来打开url地址对应的HTML页面
cat_img = response.read()               #读取数据

with open('cat01.jpg','wb') as f:       #上下文管理器生成jpg文件保存数据
    f.write(cat_img)
print(response.geturl())    #geturl  展示的是url地址
print(response.info())      #info    展示一个对象,对象包含了远程服务器返回的head信息
print(response.getcode())   #getcode 返回HTTP的状态,200表示ok

二、爬虫异常处理

import urllib.request
import urllib.error

#这里的url地址:http://www.ooxx-fishc.com    是不存在的
req = urllib.request.Request('http://www.ooxx-fishc.com')

try:    #尝试获取内容,获取不到或者出现其他错误,转入except
    html = urllib.request.urlopen('http://www.baidu.com/ooxx.html')
    print(html)
except urllib.error.HTTPError as e:
    print(e.code)
    print(e.read())

猜你喜欢

转载自blog.csdn.net/sui_yi123/article/details/83511375