addHTMLanchore.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import re
  2. def add_html_links(html: str) -> str:
  3. """
  4. Если в коде есть ссылки просто текстом, без хтмл элемента а, то функция
  5. заменит их все на полноценный html тэг с нужным атрибутом href
  6. """
  7. html = fix_links_with_brakets(html)
  8. html_cleared = html.replace('="htt', '') # remove any src and href patterns
  9. links = []
  10. for p in html_cleared.strip().split('http'):
  11. if p.startswith('://') or p.startswith('s://'):
  12. p = p.split('\n')
  13. p[0] = p[0].split('<')[0]
  14. links.append('http' + p[0])
  15. for l in links:
  16. link = ' '.join(l.split()) # убираем символы другой кодировки, которые
  17. # не убираются по-другому
  18. a_elem = f'<a href="{link}">{link}</a>'
  19. html = html.replace(l, a_elem)
  20. return html
  21. # костыль от дурака, от плохих ссылок
  22. # <a href="http://(https://pay.raschet.by
  23. def fix_links_with_brakets(html: str) -> str:
  24. html = ' '.join(html.split()) # убираем символы другой кодировки, которые
  25. result = re.findall('<a href="http://\([а-яА-Яa-zA-Z0-9\(\):/\._#>" =]+<\/a>', html)
  26. if result:
  27. for shitlink in result:
  28. if '(' in shitlink:
  29. result = result[0]
  30. link = result.split('(')[1].split(')')[0]
  31. anchor = result.split('</a>')[0].split('>')[-1].strip()
  32. a_tag = f'<a href="{link}">{anchor}</a>'
  33. html = html.replace(result, a_tag)
  34. return html