stanis-tits-scrap/stanis-tits.py

157 lines
5.0 KiB
Python
Raw Permalink Normal View History

2016-10-28 00:29:36 +03:00
#!/usr/bin/env python3
2022-09-16 01:05:33 +03:00
"""Скрипт для скачивания голых и не только девушек с блога blog.stanis.ru"""
2016-10-28 00:29:36 +03:00
import re
import shutil
import os.path
2016-11-13 16:05:25 +03:00
import requests
from bs4 import BeautifulSoup
2022-09-16 02:55:28 +03:00
import click
2016-10-28 00:29:36 +03:00
2022-09-15 22:57:19 +03:00
__author__ = "Alexander Popov"
2022-09-19 22:16:09 +03:00
__version__ = "1.0.4"
2022-09-15 22:57:19 +03:00
__license__ = "Unlicense"
2016-10-28 00:29:36 +03:00
2022-09-16 00:46:17 +03:00
# Путь к директории для загрузки изображений
DOWNLOAD_DIRECTORY = "./images"
2022-09-16 02:55:28 +03:00
# Количество загружаемых страниц
DOWNLOAD_PAGES = 0
def print_version(ctx, param, value):
if not value or ctx.resilient_parsing:
return
click.echo("Версия: {0}".format(__version__))
ctx.exit()
@click.command(add_help_option=False)
@click.option(
"--directory",
default="./images",
help="Путь к директории для загрузки изображений.",
)
@click.option("--pages", default=0, help="Количество загружаемых страниц.")
@click.option(
"--version",
"-v",
is_flag=True,
callback=print_version,
is_eager=True,
help="Отобразить версию программы.",
)
@click.help_option("--help", "-h", help="Показать эту справку")
def click(directory, pages, version):
DOWNLOAD_DIRECTORY = directory
DOWNLOAD_PAGES = pages
main(DOWNLOAD_DIRECTORY, DOWNLOAD_PAGES)
2016-11-13 16:05:25 +03:00
2022-09-16 00:46:17 +03:00
def get_images_links(page):
"""В качестве аргумента получает номер страницы
и возвращает списком адреса всех изображений"""
# На сайте фильтр изображений настроен через cookies
# Так что устанавливаем их в нужное положение
cookies = dict(block="951")
2017-03-07 16:11:50 +03:00
2022-09-16 00:46:17 +03:00
# Загружаем страницу и подсовываем её парсеру с необходимыми параметрами
r = requests.get(
"http://blog.stanis.ru/?back={0}".format(
page,
),
cookies=cookies,
)
2022-09-15 22:57:19 +03:00
soup = BeautifulSoup(
r.text.encode("cp1251"), "html.parser", from_encoding="windows-1251"
)
2017-03-07 16:11:50 +03:00
2022-09-16 00:46:17 +03:00
# Получаем все теги <img> на странице
img_tags = soup.findAll("img", src=re.compile("img/*"))
2017-03-07 16:11:50 +03:00
2022-09-16 00:46:17 +03:00
# Получаем все адреса изображений и сохраняем их в список img_links
img_links = list()
for image in img_tags:
img_links.append(image["src"].split("/")[1])
2017-03-07 16:11:50 +03:00
2022-09-16 00:46:17 +03:00
return img_links
2017-03-07 16:11:50 +03:00
2022-09-16 00:46:17 +03:00
def image_download(image):
"""В качестве аргумента получает уникальное имя изображения,
скачивает и сохраняет его на диск"""
2017-03-07 16:11:50 +03:00
2022-09-15 22:57:19 +03:00
response = requests.get(
"https://blog.stanis.ru/imgs/{0}".format(
image,
),
stream=True,
)
2017-03-07 16:11:50 +03:00
2022-09-16 00:46:17 +03:00
image_size = int(response.headers.get("Content-Length", 0))
2017-03-07 16:11:50 +03:00
2022-09-16 00:46:17 +03:00
if (
2022-09-16 02:07:38 +03:00
not os.path.exists("{0}/{1}".format(DOWNLOAD_DIRECTORY, image))
or int(os.path.getsize("{0}/{1}".format(DOWNLOAD_DIRECTORY, image)))
!= image_size
2022-09-16 00:46:17 +03:00
):
with open("{0}/{1}".format(DOWNLOAD_DIRECTORY, image), "wb") as out_image:
shutil.copyfileobj(
response.raw,
out_image,
)
2017-03-07 16:11:50 +03:00
2022-09-19 22:16:09 +03:00
return True
else:
return False
2017-03-07 16:11:50 +03:00
2022-09-16 02:55:28 +03:00
def main(download_directory, download_pages):
2022-09-16 00:46:17 +03:00
"""Главный цикл программы"""
2022-09-16 02:55:28 +03:00
if not os.path.exists(download_directory):
os.mkdir(download_directory)
2022-09-16 00:46:17 +03:00
current_page = 0
downloaded_counter = 0
2022-09-16 02:12:15 +03:00
spinner = ["◢◣◤◥", "◰◳◲◱", "◴◷◶◵", "◐◓◑◒", "|/-\\"]
spinner_id = 0
2022-09-16 00:46:17 +03:00
while True:
try:
# Получаем адреса изображений и сортируем их в порядке возрастания
images = get_images_links(current_page)
images.sort()
2022-09-16 02:55:28 +03:00
# Проверка на количество загруженных страниц
# аргумент --pages
if current_page >= download_pages and download_pages != 0:
print("\nВсего загружено {0} файлов.".format(downloaded_counter))
quit()
2022-09-16 00:46:17 +03:00
# По очереди скачиваем изображения
for image in images:
2022-09-19 22:16:09 +03:00
if image_download(image):
downloaded_counter += 1
2022-09-16 00:46:17 +03:00
2022-09-16 02:12:15 +03:00
print(
"\r{spinner} Загружено {total_files} файлов.".format(
total_files=downloaded_counter, spinner=spinner[2][spinner_id]
),
end="",
)
if spinner_id < 3:
spinner_id += 1
else:
spinner_id = 0
2022-09-16 02:07:38 +03:00
2022-09-16 00:46:17 +03:00
current_page += 1
except KeyboardInterrupt:
2022-09-16 02:55:28 +03:00
print("\nВсего загружено {0} файлов.".format(downloaded_counter))
2022-09-16 00:46:17 +03:00
quit()
2022-09-16 02:55:28 +03:00
if __name__ == "__main__":
click()