main.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. def scrape(url):
  8. data = requests.get(url)
  9. our_path = re.sub(r".*://.*/", "/", request.url)
  10. path = re.sub(r".*://.*/", "/", data.url)
  11. print(our_path, path)
  12. if our_path != path:
  13. return f"REDIRECT {path}"
  14. ret = []
  15. soup = BeautifulSoup(data.text, "html.parser")
  16. for div in soup.find_all("div"):
  17. defid = div.get('data-defid')
  18. if defid != None:
  19. definition = soup.find(attrs={"data-defid": [defid]})
  20. word = definition.select("div div h1 a, div div h2 a")[0].text
  21. meaning = definition.find(attrs={"class" : ["break-words meaning mb-4"]}).decode_contents()
  22. example = definition.find(attrs={"class" : ["break-words example italic mb-4"]}).decode_contents()
  23. contributor = definition.find(attrs={"class" : ["contributor font-bold"]})
  24. ret.append([defid, word, meaning, example, contributor])
  25. pages = soup.find(attrs={"class" : ["pagination text-xl text-center"]})
  26. if pages == None:
  27. pages = ""
  28. return (ret, pages)
  29. def render(data):
  30. return render_template('index.html', data=data)
  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. scraped = (scraped[0], str(scraped[1]).replace("»", "»").replace("›", "›").replace("«", "«").replace("‹", "‹"))
  39. return render(scraped)
  40. if __name__ == '__main__':
  41. app.run(port=8000)