簡體   English   中英

如何將 web 抓取的圖片保存到文件夾中? (Python)

[英]How to save images to a folder from web scraping? (Python)

我如何才能將我從 web 抓取中獲得的每張圖像存儲到一個文件夾中? 我目前使用 Google Colab,因為我只是在練習。 我想將它們存儲在我的 Google Drive 文件夾中。

這是我的 web 抓取代碼:

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)

我在腳本運行的文件夾中手動創建了一個pics文件夾,用於將圖片存儲在其中。 比起我在 for 循環中更改了您的代碼,以便將其附加 url 到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")
foo.write('whatever')
foo.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM