Devpal18's picture
Update app.py
f3a594f verified
Raw
History Blame Contribute Delete
1.34 kB
import requests
import pandas as pd
import gradio as gr
headers = {
"User-Agent": "Mozilla/5.0",
"Accept": "application/json"
}
def scrape_1mg(url):
try:
# Extract category slug from URL
if "categories" not in url:
return "Please enter a valid 1mg category URL."
slug = url.split("/")[-1]
api_url = f"https://www.1mg.com/api/v1/categories/{slug}/products?page=1"
response = requests.get(api_url, headers=headers)
if response.status_code != 200:
return "API request failed."
data = response.json()
products = data.get("data", [])
if not products:
return "No products found."
rows = []
for product in products:
rows.append({
"Name": product.get("name"),
"Price": product.get("price"),
"Rating": product.get("rating"),
"Discount": product.get("discount_percent")
})
df = pd.DataFrame(rows)
df.to_csv("products.csv", index=False)
return df
except Exception as e:
return str(e)
iface = gr.Interface(
fn=scrape_1mg,
inputs=gr.Textbox(label="Enter 1mg Category URL"),
outputs="dataframe",
title="1mg Category Scraper (JSON API Version)"
)
iface.launch()