如何使我從網路抓取中獲得的每個影像都存盤到一個檔案夾中?我目前使用 Google Colab,因為我只是在練習。我想將它們存盤在我的 Google Drive 檔案夾中。
這是我的網頁抓取代碼:
import requests
from bs4 import BeautifulSoup
def getdata(url):
r = requests.get(url)
return r.text
htmldata = getdata('https://www.yahoo.com/')
soup = BeautifulSoup(htmldata, 'html.parser')
imgdata = []
for i in soup.find_all('img'):
imgdata = i['src']
print(imgdata)
uj5u.com熱心網友回復:
我在運行腳本的檔案夾中手動創建了一個圖片檔案夾,以在其中存盤圖片。比我在 for 回圈中更改了您的代碼,以便將其附加到imgdata串列中。該try except塊在那里,因為并非串列中的每個 url 都是有效的。
import requests
from bs4 import BeautifulSoup
def getdata(url):
r = requests.get(url)
return r.text
htmldata = getdata('https://www.yahoo.com/')
soup = BeautifulSoup(htmldata, 'html.parser')
imgdata = []
for i in soup.find_all('img'):
imgdata.append(i['src']) # made a change here so its appendig to the list
filename = "pics/picture{}.jpg"
for i in range(len(imgdata)):
print(f"img {i 1} / {len(imgdata) 1}")
# try block because not everything in the imgdata list is a valid url
try:
r = requests.get(imgdata[i], stream=True)
with open(filename.format(i), "wb") as f:
f.write(r.content)
except:
print("Url is not an valid")
uj5u.com熱心網友回復:
foo.write('whatever')
foo.close()
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/480113.html
