下面的代码可以将图像下载到我的计算机中。但是,当我打开图像时,出现以下错误消息:“看来我们不支持此文件格式”。即使文件扩展名为.png,我的代码也肯定有问题。
import csv
import requests
with open('rlth.csv', 'r', newline='') as file:
has_header = csv.Sniffer().has_header(file.read(1024))
file.seek(0) # Rewind.
reader = csv.reader(file)
if has_header:
next(reader) # Skip header row.
csvrows = csv.reader(file, delimiter=',', quotechar='"')
for row in csvrows:
filename = row[0]
url = row[2]
result = requests.get(url, stream=True)
if result.status_code == 200:
image = result.raw.read()
open("{}.png".format(filename),"wb").write(image)
下面是rlth.csv的一瞥:
identifier link likes_count company
0 2293876619351464318 https://www.instagram.com/p/B_VfKG_BJl- 175 Ralph Lauren
1 2293779660171363517 https://www.instagram.com/p/B_VJHKth8S9 3263 Ralph Lauren
2 2293716498600285587 https://www.instagram.com/p/B_U6wC6hdWT 12617 Ralph Lauren
3 2293068067321995905 https://www.instagram.com/p/B_SnUIOhOKB 8430 Ralph Lauren
4 2293002309485390353 https://www.instagram.com/p/B_SYXOeBuoR 7452 Ralph Lauren