Spaces:
Runtime error
Runtime error
# fastapi_server.py | |
from fastapi import FastAPI | |
import requests | |
from bs4 import BeautifulSoup | |
import re | |
app = FastAPI() | |
# Function to scrape only visible text from the given URL | |
def scrape_visible_text_from_url(url): | |
try: | |
response = requests.get(url) | |
response.raise_for_status() | |
soup = BeautifulSoup(response.content, 'html.parser') | |
# Remove script, style, and other non-visible tags | |
for tag in soup(["script", "style", "meta", "link", "noscript", "header", "footer", "aside", "nav", "img"]): | |
tag.extract() | |
# Get the header content | |
header_content = soup.find("header") | |
header_text = header_content.get_text() if header_content else "" | |
# Get the paragraph content | |
paragraph_content = soup.find_all("p") | |
paragraph_text = " ".join([p.get_text() for p in paragraph_content]) | |
# Combine header and paragraph text | |
visible_text = f"{header_text}\n\n{paragraph_text}" | |
# Remove multiple whitespaces and newlines | |
visible_text = re.sub(r'\s+', ' ', visible_text) | |
return visible_text.strip() | |
except Exception as e: | |
return str(e) | |
async def root(url: str): | |
data = scrape_visible_text_from_url(url) | |
return {"scraped_text": data} | |