Spaces:
Paused
Paused
Update app.py
Browse files3 unmodified lines4567891011121314151617183 unmodified lines2223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411423 unmodified linesimport refrom playwright.sync_api import sync_playwrightst.set_page_config(page_title="CineMM Scraper Master", page_icon="🎬")st.title("🎬 CineMM Movie Scraper Master")st.write("Final refined version for direct MP4 links and full poster URLs.")query = st.text_input("Enter Search Query (e.g., 2026):", "2026")num_movies = st.slider("Number of movies to scrape:", 1, 20, 5)def scrape_cinemm_master(search_query, limit):movies_data = []base_storage_url = "https://stream.cmapp.tv/file/"3 unmodified linespage = context.new_page()try:url = f"https://cinemm.com/?search={search_query}&type=movie"st.info(f"Searching CineMM...")page.goto(url, timeout=60000, wait_until="networkidle")# Wait for resultspage.wait_for_selector("h3", timeout=30000)time.sleep(3)cards = page.query_selector_all("div.cursor-pointer")st.info(f"Found {len(cards)} movies. Processing top {limit}...")for i in range(min(len(cards), limit)):try:# Re-fetch cardscards = page.query_selector_all("div.cursor-pointer")if i >= len(cards): breakcard = cards[i]# Extract basic info from cardtitle_el = card.query_selector("h3")title = title_el.inner_text().strip() if title_el else "Unknown"img_el = card.query_selector("img")poster_path = img_el.get_attribute("src") if img_el else ""# Fix poster URL if it's relativeif poster_path and not poster_path.startswith("http"):# If it starts with /file/, prepend the base storage URLif poster_path.startswith("/file/"):poster_url = "https://stream.cmapp.tv" + poster_pathelse:poster_url = base_storage_url + poster_pathelse:poster_url = poster_path# Click to get direct linkscard.click()page.wait_for_selector("h1", timeout=20000)time.sleep(3) # Wait for download buttons to load# Extract direct MP4 link from buttonsdirect_url = "N/A"buttons = page.query_selector_all("button")for btn in buttons:btn_text = btn.inner_text()# Look for buttons that look like download links (contain size info)if "GB" in btn_text or "MB" in btn_text:# We try to capture the link by clicking or looking at the button's behavior# In this specific site, clicking often opens the direct linkwith page.expect_navigation(timeout=10000) as nav:btn.click()try:nav_info = nav.valueif nav_info and (".mp4" in nav_info.url or ".mkv" in nav_info.url or "stream" in nav_info.url):direct_url = nav_info.urlbreakexcept:# If navigation doesn't happen, the link might be in a different waypass# If still N/A, use the current page URL as fallbackif direct_url == "N/A":direct_url = page.url# Extract genre and year from detail pagebody_text = page.inner_text("body")genre = "N/A"if "Genre…." in body_text:genre = body_text.split("Genre….")[1].split("Duration")[0].strip()year = "N/A"year_match = re.search(r"\b(20\d{2}|19\d{2})\b", body_text)if year_match:year = year_match.group(1)movies_data.append({"logo": poster_url,"url": direct_url,"name": title,"year": year,"genre": genre})# Go back to search resultspage.goto(url, wait_until="networkidle")page.wait_for_selector("h3", timeout=20000)time.sleep(1)except Exception as e:st.warning(f"Error processing movie {i+1}: {e}")page.goto(url)continueexcept Exception as e:st.error(f"Scraping failed: {e}")finally:browser.close()return movies_dataif st.button("Start Master Scraping"):if not query:st.error("Please enter a search query.")else:with st.spinner("Scraping... This will take a few minutes as it fetches direct links."):data = scrape_cinemm_master(query, num_movies)if data:st.success(f"Successfully scraped {len(data)} movies!")st.json(data)json_str = json.dumps(data, ensure_ascii=False, indent=4)st.download_button(label="Download JSON",data=json_str,file_name=f"cinemm_master_{query}.json",mime="application/json")else:3 unmodified lines4567891011121314151617183 unmodified lines2223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421433 unmodified linesimport refrom playwright.sync_api import sync_playwrightst.set_page_config(page_title="CineMM Scraper Bulletproof", page_icon="🎬")st.title("🎬 CineMM Movie Scraper Bulletproof")st.write("Most stable version using direct navigation and robust link extraction.")query = st.text_input("Enter Search Query (e.g., 2026):", "2026")num_movies = st.slider("Number of movies to scrape:", 1, 20, 5)def scrape_cinemm_bulletproof(search_query, limit):movies_data = []base_storage_url = "https://stream.cmapp.tv/file/"3 unmodified linespage = context.new_page()try:search_url = f"https://cinemm.com/?search={search_query}&type=movie"st.info(f"🔍 Searching: {search_query}")page.goto(search_url, timeout=60000, wait_until="networkidle")# Wait for resultspage.wait_for_selector("h3", timeout=30000)time.sleep(3)# Extract movie links first to avoid stale elementsmovie_links = []cards = page.query_selector_all("div.cursor-pointer")for card in cards:title_el = card.query_selector("h3")img_el = card.query_selector("img")title = title_el.inner_text().strip() if title_el else "Unknown"poster_path = img_el.get_attribute("src") if img_el else ""# We need to get the ID or slug to build the direct URL# Since we can't easily get the href from the div, we'll use the click-and-capture-URL method# but we'll do it more carefully.movie_links.append({"title": title,"poster": poster_path})st.info(f"✅ Found {len(movie_links)} movies. Processing...")for i in range(min(len(movie_links), limit)):try:movie = movie_links[i]st.write(f"⏳ Processing ({i+1}/{limit}): **{movie['title']}**")# Go back to search page to click the next moviepage.goto(search_url, wait_until="networkidle")page.wait_for_selector("h3", timeout=30000)time.sleep(2)# Click the i-th cardcurrent_cards = page.query_selector_all("div.cursor-pointer")if i < len(current_cards):current_cards[i].click()page.wait_for_selector("h1", timeout=30000)time.sleep(3)detail_url = page.urlbody_text = page.inner_text("body")# Extract Direct Linkdirect_url = detail_url # Default# Look for any link that looks like a stream or download# We can also look for the specific pattern in the HTMLhtml_content = page.content()# Try to find links in the HTML that contain .mp4 or .mkvmp4_links = re.findall(r'https?://[^\s<>"]+\.(?:mp4|mkv)[^\s<>"]*', html_content)if mp4_links:direct_url = mp4_links[0]else:# Try to find stream linksstream_links = re.findall(r'https?://stream\.[^\s<>"]+', html_content)if stream_links:direct_url = stream_links[0].split('"')[0].split("'")[0]# Fix Poster URLposter_path = movie['poster']if poster_path and not poster_path.startswith("http"):if poster_path.startswith("/file/"):poster_url = "https://stream.cmapp.tv" + poster_pathelse:poster_url = base_storage_url + poster_pathelse:poster_url = poster_path# Extract Genre & Yeargenre = "N/A"if "Genre…." in body_text:genre = body_text.split("Genre….")[1].split("Duration")[0].strip()year = "N/A"year_match = re.search(r"\b(20\d{2}|19\d{2})\b", body_text)if year_match:year = year_match.group(1)movies_data.append({"logo": poster_url,"url": direct_url,"name": movie['title'],"year": year,"genre": genre})except Exception as inner_e:st.warning(f"⚠️ Error on movie {i+1}: {inner_e}")continueexcept Exception as e:st.error(f"❌ Scraping failed: {e}")finally:browser.close()return movies_dataif st.button("Start Bulletproof Scraping"):if not query:st.error("Please enter a search query.")else:with st.spinner("🚀 Scraping in progress..."):data = scrape_cinemm_bulletproof(query, num_movies)if data:st.success(f"🎉 Successfully scraped {len(data)} movies!")st.json(data)json_str = json.dumps(data, ensure_ascii=False, indent=4)st.download_button(label="📥 Download JSON",data=json_str,file_name=f"cinemm_stable_{query}.json",mime="application/json")else:
app.py+91-90