requests抓取二进制数据

想必大家思考过,我如果把网上的图片,视频爬下来,那我怎么保存在本地呢?因为图片,视频本身是二进制流。所以,想要抓取它们,就要拿到它们的二进制码。

以GitHub的站点图标为例。

from bs4 import BeautifulSoup
import requests, sys
import lxml

response = requests.get('https://github.com/favicon.ico')
#response.text为str类型
print(response.text)
print(response.content)

                                                                                           运行结果

前者出现乱码,是因为图片是二进制数据,所以前者打印转化为str类型,肯定会出现乱码呀。而后者结果带有一个b,代表是bytes类型的数据。

接着,我们把刚才提取的图片保存下来:

with open('favicon.ico','wb') as f:
    f.write(response.content)

同样的,音频和视频文件也可以这样获取。

发布了178 篇原创文章 · 获赞 14 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_40511966/article/details/103865443