Помогите распарсить этот сайт чтобы он парсил картинки и скачивал их

from bs4 import  BeautifulSoup import requests from time import sleep

def getImages(url):   sleep(2)   HEADERS = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36'}

  responce = requests.get(url, headers=HEADERS)   soup = BeautifulSoup(responce.content, 'html.parser')   items = soup.findAll('div', class_='lazy-loaded')   comps = []

  for item in items:
    comps.append(item.find('img').get('src'))

  print(comps)

getImages('https://www.wallpaperflare.com/search?wallpaper=anime&sort=relevance')

Ответы (1 шт):

Автор решения: Johan

Не знаю, насколько быстро все это будет происходить, но думаю, что не один час, так как там больше 15000 изображений. Можно сделать примерно вот так:

import os.path
import threading
import time

import requests
from bs4 import BeautifulSoup

HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 '
                  'Safari/537.36 ',
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,'
              'application/signed-exchange;v=b3;q=0.9 '
}


def get_links_images():
    print(f'[+] Поиск ссылок на страницах')
    image_pages = []
    num_page = 1
    while True:
        url = f'https://www.wallpaperflare.com/search?wallpaper=anime&sort=relevance&page={num_page}'
        resp = requests.get(url, headers=HEADERS)
        soup = BeautifulSoup(resp.content, 'html.parser')
        try:
            find_all_li = soup.find('ul', class_='gallery').find_all('li', itemprop="associatedMedia")
            for li in find_all_li:
                link_img_page = li.find('figure').find('a', itemprop="url")['href']
                image_pages.append(link_img_page)
            print(f'\r  - Загружаю ссылки со страницы: {num_page}', end='')
            num_page += 1
        except AttributeError:
            return image_pages


def get_download(url):
    resp = requests.get(url=url, headers=HEADERS)
    soup = BeautifulSoup(resp.content, 'html.parser')
    try:
        link_img = soup.find('a', class_='link_btn aq mt20')['href']
        img_page = requests.get(url=link_img, headers=HEADERS)
        soup = BeautifulSoup(img_page.content, 'html.parser')
        img_link = soup.find('img', itemprop="contentUrl")['src']
        img_name = img_link.split("/")[-1]
        dir_path = f'{img_name.split("-")[1]}_{img_name.split("-")[2]}'
        img_download = requests.get(url=img_link, headers=HEADERS).content
        print(f'\rЗагрузка: {img_link}', end='')

        if not os.path.exists(os.path.join(os.getcwd(), 'wallpaper', dir_path)):
            os.mkdir(os.path.join(os.getcwd(), 'wallpaper', dir_path))

        save_path = os.path.join(os.getcwd(), 'wallpaper', dir_path, img_name)
        with open(save_path, 'wb') as img:
            img.write(img_download)
    except TypeError:
        return


def download(image_pages):
    threads = []

    if not os.path.exists(os.path.join(os.getcwd(), 'wallpaper')):
        os.mkdir(os.path.join(os.getcwd(), 'wallpaper'))

    print('\n\n[+]Загрузка картинок')
    print(f'[+] Найдено картинок: {len(image_pages)}\n')
    for url in image_pages:
        t = threading.Thread(target=get_download, kwargs={'url': url})
        t.daemon = True
        t.start()
        threads.append(t)
        time.sleep(0.05)

    for thread in threads:
        thread.join()


def main():
    start_time = time.monotonic()
    image_pages = get_links_images()
    download(image_pages)
    print('\n\nЗагрузка завершена')
    print(f'Время затраченное на загрузку: {time.monotonic() - start_time}')


if __name__ == "__main__":
    main()
→ Ссылка