main.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #!/usr/bin/env python
  2. from flask import Flask, render_template, request, redirect
  3. import requests
  4. import html
  5. import re
  6. from bs4 import BeautifulSoup
  7. from urllib.parse import quote, unquote
  8. def scrape(url):
  9. data = requests.get(url)
  10. our_path = re.sub(r".*://.*/", "/", request.url)
  11. path = re.sub(r".*://.*/", "/", data.url)
  12. if our_path != path and \
  13. quote(unquote(re.sub("[?&=]", "", our_path))) != re.sub("[?&=]", "", path):
  14. # this is bad ^
  15. return f"REDIRECT {path}"
  16. ret = []
  17. soup = BeautifulSoup(data.text, "html.parser")
  18. for div in soup.find_all("div"):
  19. defid = div.get('data-defid')
  20. if defid != None:
  21. definition = soup.find(attrs={"data-defid": [defid]})
  22. word = definition.select("div div h1 a, div div h2 a")[0].text
  23. meaning = definition.find(attrs={"class" : ["break-words meaning mb-4"]}).decode_contents()
  24. example = definition.find(attrs={"class" : ["break-words example italic mb-4"]}).decode_contents()
  25. contributor = definition.find(attrs={"class" : ["contributor font-bold"]})
  26. ret.append([defid, word, meaning, example, contributor])
  27. pages = soup.find(attrs={"class" : ["pagination text-xl text-center"]})
  28. if pages == None:
  29. pages = ""
  30. return (ret, pages)
  31. app = Flask(__name__, template_folder="templates", static_folder="static")
  32. @app.route('/', defaults={'path': ''})
  33. @app.route('/<path:path>')
  34. def catch_all(path):
  35. scraped = scrape(f"https://urbandictionary.com/{re.sub(r'.*://.*/', '/', request.url)}")
  36. if type(scraped) == str and scraped.startswith("REDIRECT"):
  37. return redirect(scraped.replace("REDIRECT ", ""), 302)
  38. return render_template('index.html', data=scraped)
  39. if __name__ == '__main__':
  40. app.run(port=8000)