Advertisement
usrxprd

mainchanrandom

Feb 9th, 2025
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.55 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3. # A CGI script that redirects the user to a random Mainchan subchan.
  4. # Note: This script may be slow and wasteful of data because the subchan
  5. #       list is scraped each time this script runs.
  6.  
  7. import random
  8. import requests
  9. from bs4 import BeautifulSoup
  10.  
  11. def getSubList():
  12.     sublist = []
  13.  
  14.     headers = {'User-Agent': 'mainchanrandom scraper'}
  15.  
  16.     n = 1
  17.     while n < 10:   # the n < 10 check is for the loop to not iterate forever just incase the 'no links in table' check will fail
  18.         url = f'https://mainchan.com/subchan-list?page={n}'
  19.         sublist_page = requests.get(url, headers=headers)
  20.  
  21.         soup = BeautifulSoup(sublist_page.content, "html.parser")
  22.         sublist_table = soup.find("table", class_="sublist-table")  # finds first occurence of table tag
  23.         sublinks = sublist_table.find_all("a")
  24.         if not sublinks:    # if there are no links in the table, then we have reached the end of the pages
  25.             break
  26.         for link in sublinks:
  27.             sublist.append(link["href"])
  28.  
  29.         n = n + 1
  30.  
  31.     return sublist
  32.  
  33. sublist = getSubList()
  34. randomsub_url = sublist[random.randint(0, len(sublist)-1)]
  35.  
  36. print("Content-Type: text/html")
  37. print(f"Location: {randomsub_url}")
  38. print("\r\n\r\n", end='')
  39. print("<html>")
  40. print("  <head>")
  41. print(f"   <meta http-equiv='refresh' content='0;url={randomsub_url}'/>")
  42. print("    <title>Redirecting...</title>")
  43. print("  </head>")
  44. print("  <body>")
  45. print("    <center>")
  46. print(f"     <p>Redirecting... <br><a href={randomsub_url}>click here</a> if it doesn't work</p>")
  47. print("    </center>")
  48. print("  </body>")
  49. print("</html>")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement