Skip to content

Instantly share code, notes, and snippets.

@phoenixthrush
Last active June 18, 2024 20:20
Show Gist options
  • Save phoenixthrush/24236b6be758bd41474d2184615f1271 to your computer and use it in GitHub Desktop.
Save phoenixthrush/24236b6be758bd41474d2184615f1271 to your computer and use it in GitHub Desktop.
Python nHentai Downloader
import os
import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
from bs4 import BeautifulSoup
import re
COLORS = {
'pink': '\033[38;5;219m',
'cyan': '\033[38;5;51m',
'green': '\033[38;5;156m',
'red': '\033[38;5;196m',
'reset': '\033[0m',
'clear': '\033[H\033[2J'
}
def get_input(prompt):
return input(f"{prompt}{COLORS['cyan']}> {COLORS['reset']}")
def create_output_folder(folder_name):
output_path = os.path.join(os.path.expanduser("~/Downloads"), folder_name)
os.makedirs(output_path, exist_ok=True)
return output_path
def download_image(image_url, output_path, i):
try:
response = requests.get(image_url)
if response.status_code == 200 and response.content.startswith(b'\xff\xd8'):
image_path = os.path.join(output_path, f'{i}.jpg')
with open(image_path, 'wb') as image_file:
image_file.write(response.content)
return f"Image {i} downloaded."
except requests.RequestException as e:
return f"Error downloading image {i}: {e}"
return None
def download_images_concurrently(base_url, output_path):
with ThreadPoolExecutor(os.cpu_count() * 2) as executor:
futures = {
executor.submit(download_image, f"{base_url}/{i}.jpg", output_path, i): i
for i in range(1, 1000)
}
for future in as_completed(futures):
result = future.result()
if result:
print(f"{COLORS['green']}{result}{COLORS['reset']}", end='\r')
else:
break
def fetch_image_base_url(gallery_id):
page_url = f"https://nhentai.net/g/{gallery_id}/1"
try:
response = requests.get(page_url)
if response.status_code == 200:
soup = BeautifulSoup(response.content, 'html.parser')
img_tag = soup.select_one('#image-container a img')
if img_tag:
img_url = img_tag['src']
match = re.match(r'https://(\w+)\.nhentai\.net/galleries/(\d+)/\d+\.jpg', img_url)
if match:
subdomain, gallery_id = match.groups()
return f"https://{subdomain}.nhentai.net/galleries/{gallery_id}"
except requests.RequestException:
return None
def main():
print(COLORS['clear'], end='')
source = get_input(f"{COLORS['pink']}Please provide the image source for any doujin image.")
folder = get_input(f"{COLORS['pink']}\nWhat should the output folder be called?")
output_path = create_output_folder(folder)
base_url = fetch_image_base_url(source)
if base_url:
download_images_concurrently(base_url, output_path)
else:
print(f"{COLORS['red']}Error: Unable to fetch the base URL for images.{COLORS['reset']}")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment