1.打开http://placekitten.com,下载小猫的图片
第一种方法
import urllib.request
response=urllib.request.urlopen("http://placekitten.com/500/500")
cat_img=response.read()
with open('cat_500_500.jfif','wb') as f:
f.write(cat_img)
程序运行结果
第二种方法
实例化Request,创建一个request对象
import urllib.request
req=urllib.request.Request("http://placekitten.com/500/500")
response=urllib.request.urlopen(req)
cat_img=response.read()
with open('cat_500_500.jfif','wb') as f:
f.write(cat_img)
2.除了使用read方法获取对象中的内容,我们还可以访问具体地址
>>> response.geturl()
'http://placekitten.com/500/500'
>>>
3.得到对象
>>> response.info()
<http.client.HTTPMessage object at 0x000001C930324EF0>
>>>
4.输出:包含了远程服务器cloudflare的head信息
>>> print(response.info())
Date: Thu, 10 Sep 2020 12:42:50 GMT
Content-Type: image/jpeg
Transfer-Encoding: chunked
Connection: close
Set-Cookie: __cfduid=d8f619a2c2ffe123f9c81964fc09fbbad1599741770; expires=Sat, 10-Oct-20 12:42:50 GMT; path=/; domain=.placekitten.com; HttpOnly; SameSite=Lax
Cache-Control: public, max-age=86400
Expires: Thu, 31 Dec 2020 20:00:00 GMT
Vary: User-Agent, Accept-Encoding
Access-Control-Allow-Origin: *
CF-Cache-Status: HIT
Age: 43225
cf-request-id: 0519a353370000ed8f89017200000001
Server: cloudflare
CF-RAY: 5d093b31fb52ed8f-SJC
5.200表示服务器的ok状态,即正常响应
>>> response.getcode ()
200
>>>