/
ksushaksusha
/
Python
Обзор
Документация
Войти
/
ksushaksusha
/
Python
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
web_programming/random_anime_character.py
48 строк
1 KB
Christian Clauss
Lukazlim: Replace dependency `requests` with `httpx` (#12744)
14 май 2025, 04:42
Не верифицирован
14 май 2025, 04:42
a2fa32c
Код
Авторство
О чём код?
# /// script # requires-python = ">=3.13" # dependencies = [ # "beautifulsoup4", # "fake-useragent", # "httpx", # ] # /// import os import httpx from bs4 import BeautifulSoup from fake_useragent import UserAgent headers = {"UserAgent": UserAgent().random} URL = "https://www.mywaifulist.moe/random" def save_image(image_url: str, image_title: str) -> None: """ Saves the image of anime character """ image = httpx.get(image_url, headers=headers, timeout=10) with open(image_title, "wb") as file: file.write(image.content) def random_anime_character() -> tuple[str, str, str]: """ Returns the Title, Description, and Image Title of a random anime character . """ soup = BeautifulSoup( httpx.get(URL, headers=headers, timeout=10).text, "html.parser" ) title = soup.find("meta", attrs={"property": "og:title"}).attrs["content"] image_url = soup.find("meta", attrs={"property": "og:image"}).attrs["content"] description = soup.find("p", id="description").get_text() _, image_extension = os.path.splitext(os.path.basename(image_url)) image_title = title.strip().replace(" ", "_") image_title = f"{image_title}{image_extension}" save_image(image_url, image_title) return (title, description, image_title) if __name__ == "__main__": title, desc, image_title = random_anime_character() print(f"{title}\n\n{desc}\n\nImage saved : {image_title}")