t / app.py
r3hab's picture
Update app.py
2e46e4c verified
from fastapi import FastAPI, HTTPException
import requests
from bs4 import BeautifulSoup
from urllib.parse import unquote
app = FastAPI()
@app.get("/search/{query}")
async def search(query: str):
# URL of the page to scrape
url = f'http://thepiratebay7.com/search/{query}' # Replace with the actual URL
# Send a GET request to the URL
response = requests.get(url)
# Check if the request was successful
if response.status_code == 200:
# Parse the HTML content
soup = BeautifulSoup(response.content, 'html.parser')
# Find all <td> elements
td_elements = soup.find_all('td')
results = []
# Loop through each <td> element to extract data
for td in td_elements:
# Initialize title and link variables
title = 'N/A'
link = 'N/A'
# Find the title and magnet link
title_div = td.find('div', class_='detName')
if title_div:
title_link = title_div.find('a')
title = title_link.text if title_link else 'N/A'
link = title_link['href'] if title_link else 'N/A'
magnet_link = td.find('a', href=lambda href: href and href.startswith('magnet:'))
magnet = magnet_link['href'] if magnet_link else 'N/A'
# Decode the magnet link if it's not 'N/A'
if magnet != 'N/A':
magnet = unquote(magnet)
# Append the extracted data to results
results.append({'File Name': title, 'Magnet Link': magnet})
return {"results": results}
else:
raise HTTPException(status_code=response.status_code, detail="Failed to retrieve data")