抓取照片儲存桌面

晉陽十二夜發表於2020-12-27
import requests
from bs4 import BeautifulSoup
import os
from io import BytesIO
from PIL import Image
import time

url = "http://www.yestone.com/gallery/1501754333627"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64)"}

r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.content, 'html.parser')
items = soup.find_all('img', attrs={'data-v-32e60122': ''})
folder_path = 'C:\\Users\\Administrator\\Desktop\\images'

if os.path.exists(folder_path) == False:
    os.makedirs(folder_path)

for index, item in enumerate(items):
    if item:
        turl = item.get('src')
        if not turl.startswith('http:'):
            continue
        html = requests.get(item.get('src'))
        img_name = str(index + 1) + '.png'
        image = Image.open(BytesIO(html.content))
        image.save(folder_path + "/" + img_name)
        print('第%d張圖片下載完成' % (index + 1))
        time.sleep(1)  # 自定義延時
print('抓取完成')

 

相關文章