From eca37b1537ce9df227e1c2a915b2841093b9c028 Mon Sep 17 00:00:00 2001 From: Lucifer <63491234+ashish-patwal@users.noreply.github.com> Date: Mon, 19 Jul 2021 21:10:18 +0530 Subject: [PATCH] Random anime character info (#4553) * fixed colons and spaces * fixed colons and spaces * random anime character python script * more tests passed * type hint updated Co-authored-by: Christian Clauss * type hint updated again Co-authored-by: Christian Clauss * Update random_anime_character.py Co-authored-by: Christian Clauss --- web_programming/random_anime_character.py | 37 +++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 web_programming/random_anime_character.py diff --git a/web_programming/random_anime_character.py b/web_programming/random_anime_character.py new file mode 100644 index 000000000..f15a9c05d --- /dev/null +++ b/web_programming/random_anime_character.py @@ -0,0 +1,37 @@ +import os + +import requests +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 = requests.get(image_url, headers=headers) + 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(requests.get(URL, headers=headers).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}")