import requests
from bs4 import BeautifulSoup
import re
import os
import subprocess
from typing import List, Dict, Optional
import json
class JuliaTorrentDownloader:
"""Download Julia language torrents from 1337x"""
def __init__(self):
self.base_url = "https://1337x.to"
self.headers =
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
def search_julia_torrents(self, query: str = "julia programming language") -> List[Dict]:
"""Search for Julia related torrents"""
search_url = f"self.base_url/search/query.replace(' ', '+')/1/"
try:
response = requests.get(search_url, headers=self.headers)
response.raise_for_status()
soup = BeautifulSoup(response.content, 'lxml')
torrents = []
# Find torrent rows in the table
rows = soup.select('tbody tr')
for row in rows[:10]: # Get top 10 results
try:
title_elem = row.select_one('td.coll-1 a:nth-child(2)')
if not title_elem:
continue
title = title_elem.text.strip()
# Filter for Julia related content
if 'julia' in title.lower():
torrent =
'title': title,
'link': f"self.base_urltitle_elem.get('href')",
'seeders': row.select_one('td.coll-2').text.strip(),
'leechers': row.select_one('td.coll-3').text.strip(),
'size': row.select_one('td.coll-4').text.strip(),
'upload_date': row.select_one('td.coll-5').text.strip()
torrents.append(torrent)
except Exception as e:
print(f"Error parsing row: e")
continue
return torrents
except requests.RequestException as e:
print(f"Error searching torrents: e")
return []
def get_torrent_details(self, torrent_url: str) -> Optional[Dict]:
"""Get detailed information about a specific torrent"""
try:
response = requests.get(torrent_url, headers=self.headers)
response.raise_for_status()
soup = BeautifulSoup(response.content, 'lxml')
details = {}
# Get download link
magnet_link = soup.select_one('a[href^="magnet:"]')
if magnet_link:
details['magnet'] = magnet_link.get('href')
# Get info hash
hash_match = re.search(r'btih:([a-fA-F0-9]+)', details['magnet']) if 'magnet' in details else None
if hash_match:
details['info_hash'] = hash_match.group(1)
# Get description
description = soup.select_one('div.torrent-detail-page div.description')
if description:
details['description'] = description.text.strip()
# Get file list
files = []
file_rows = soup.select('div.file-list ul li')
for file_row in file_rows[:20]: # First 20 files
file_text = file_row.text.strip()
if file_text:
files.append(file_text)
details['files'] = files
return details
except requests.RequestException as e:
print(f"Error getting torrent details: e")
return None
def download_torrent(self, magnet_link: str, download_path: str = "./downloads"):
"""Download torrent using magnet link"""
# Create download directory
os.makedirs(download_path, exist_ok=True)
try:
# Using aria2 for better download management
cmd = [
'aria2c',
'--seed-time=0', # No seeding after download
'--max-connection-per-server=16',
'--split=16',
'--min-split-size=1M',
'--console-log-level=error',
f'--dir=download_path',
magnet_link
]
# Alternative: Use libtorrent through python
return self.download_with_libtorrent(magnet_link, download_path)
except Exception as e:
print(f"Error downloading: e")
return False
def download_with_libtorrent(self, magnet_link: str, download_path: str) -> bool:
"""Download torrent using libtorrent python bindings"""
try:
import libtorrent as lt
ses = lt.session()
ses.listen_on(6881, 6891)
params =
'save_path': download_path,
'storage_mode': lt.storage_mode_t(2),
'paused': False,
'auto_managed': True,
'duplicate_is_error': True
handle = lt.add_magnet_uri(ses, magnet_link, params)
print(f"Downloading to: download_path")
print("Fetching metadata...")
# Wait for metadata
while not handle.has_metadata():
time.sleep(1)
print("Got metadata, starting download...")
# Download until complete
while handle.status().state != lt.torrent_status.seeding:
status = handle.status()
print(f"\rProgress: status.progress * 100:.1f% | "
f"Download: status.download_rate / 1000:.1f kB/s | "
f"Seeds: status.num_seeds", end='', flush=True)
time.sleep(2)
print("\nDownload complete!")
return True
except ImportError:
print("libtorrent not available, using alternative method...")
return self.alternative_download(magnet_link, download_path)
except Exception as e:
print(f"Libtorrent error: e")
return False
def alternative_download(self, magnet_link: str, download_path: str) -> bool:
"""Alternative download method using webbit torrent"""
try:
import webbit
client = webbit.Client()
torrent = client.get_torrent(magnet_link)
# Subscribe to download events
torrent.subscribe_download(webbit.DOWNLOAD_COMPLETE,
lambda: print("Download completed!"))
torrent.download(download_path)
return True
except ImportError:
print("Install webbit: pip install webbit")
# Fallback to web download if possible
return self.web_download_fallback(magnet_link, download_path)
def web_download_fallback(self, magnet_link: str, download_path: str) -> bool:
"""Last resort fallback using requests"""
print("Opening magnet link in browser for manual download...")
import webbrowser
webbrowser.open(magnet_link)
print(f"Magnet link opened. Download to: download_path")
return True
def filter_by_version(self, torrents: List[Dict], version: str) -> List[Dict]:
"""Filter torrents by Julia version"""
filtered = []
version_pattern = re.compile(rf'julia[-_\s]*re.escape(version)', re.IGNORECASE)
for torrent in torrents:
if version_pattern.search(torrent['title']):
filtered.append(torrent)
return filtered
def get_best_torrent(self, torrents: List[Dict]) -> Optional[Dict]:
"""Select the best torrent based on seeders"""
if not torrents:
return None
# Convert seeders to int and sort
for torrent in torrents:
try:
torrent['seeders_count'] = int(torrent['seeders'].replace(',', ''))
except ValueError:
torrent['seeders_count'] = 0
return max(torrents, key=lambda x: x['seeders_count'])
Before diving into third-party sites, it's essential to note that the most straightforward and legal way to obtain Julia is through its official website: Download julia a Torrents - 1337x
pip install requests beautifulsoup4 lxml import requests from bs4 import BeautifulSoup import re
Share by: