Guest User

translate website in any language with google

a guest
Jun 22nd, 2022
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.80 KB | None | 0 0
  1. ----------------------
  2. Explanation:
  3.  
  4. ROMANIAN: https://neculaifantanaru.com/python-code-text-google-translate-website-translation-beautifulsoup-new.html
  5.  
  6. ENGLISH: https://neculaifantanaru.com/en/python-code-text-google-translate-website-translation-beautifulsoup-new.html
  7. ----------------------
  8.  
  9.  
  10.  
  11. from bs4 import BeautifulSoup
  12. from bs4.formatter import HTMLFormatter
  13. import requests
  14. import sys
  15. import os
  16.  
  17. class UnsortedAttributes(HTMLFormatter):
  18.     def attributes(self, tag):
  19.         for k, v in tag.attrs.items():
  20.             yield k, v
  21.  
  22. files_from_folder = r"c:\Folder2"
  23. use_translate_folder = True
  24. destination_language = 'vi'  #aici schimbi limba in care vrei sa traduci
  25. extension_file = ".html"
  26. directory = os.fsencode(files_from_folder)
  27.  
  28. def translate(text, target_language):
  29.     url = "https://translate.google.com/translate_a/single"
  30.     headers = {
  31.         "Host": "translate.google.com",
  32.         "Accept": "*/*",
  33.         "Cookie": "",
  34.         "User-Agent": "GoogleTranslate/5.9.59004 (iPhone; iOS 10.2; ja; iPhone9,1)",
  35.         "Accept-Language": "fr",
  36.         "Accept-Encoding": "gzip, deflate",
  37.         "Connection": "keep-alive",
  38.         }
  39.     sentence = text
  40.     params = {
  41.         "client": "it",
  42.         "dt": ["t", "rmt", "bd", "rms", "qca", "ss", "md", "ld", "ex"],
  43.         "otf": "2",
  44.         "dj": "1",
  45.         "q": sentence,
  46.         "hl": "ja",
  47.         "ie": "UTF-8",
  48.         "oe": "UTF-8",
  49.         "sl": "en",
  50.         "tl": target_language,
  51.         }
  52.  
  53.     res = requests.get(
  54.         url=url,
  55.         headers=headers,
  56.         params=params,
  57.         )
  58.  
  59.     res = res.json()
  60.  
  61.     paragraph = ''
  62.     for i in range(0, len(res["sentences"])):
  63.         paragraph += res["sentences"][i]["trans"]
  64.  
  65.     return paragraph
  66.  
  67. def recursively_translate(node):
  68.     for x in range(len(node.contents)):
  69.         if isinstance(node.contents[x], str):
  70.             if node.contents[x].strip() != '':
  71.                 try:
  72.                     node.contents[x].replaceWith(translate(text=node.contents[x], target_language=destination_language))
  73.                 except:
  74.                     pass
  75.         elif node.contents[x] != None:
  76.             recursively_translate(node.contents[x])
  77.  
  78. for file in os.listdir(directory):
  79.     filename = os.fsdecode(file)
  80.     print(filename)
  81.     if filename == 'y_key_e479323ce281e459.html' or filename == 'directory.html': #ignore this 2 files
  82.         continue
  83.     if filename.endswith(extension_file):
  84.         with open(os.path.join(files_from_folder, filename), encoding='utf-8') as html:
  85.             soup = BeautifulSoup('<pre>' + html.read() + '</pre>', 'html.parser')
  86.             for title in soup.findAll('title'):
  87.                 recursively_translate(title)
  88.  
  89.             for meta in soup.findAll('meta', {'name':'description'}):
  90.                 try:
  91.                     meta['content'] = translate(text=meta['content'], target_language=destination_language)
  92.                 except:
  93.                     pass
  94.  
  95.             for h1 in soup.findAll('h1', {'itemprop':'name'}, class_='den_articol'):
  96.                 begin_comment = str(soup).index('<!-- ARTICOL START -->')
  97.                 end_comment = str(soup).index('<!-- ARTICOL FINAL -->')
  98.                 if begin_comment < str(soup).index(str(h1)) < end_comment:
  99.                     recursively_translate(h1)
  100.  
  101.             for p in soup.findAll('p', class_='text_obisnuit'):
  102.                 begin_comment = str(soup).index('<!-- ARTICOL START -->')
  103.                 end_comment = str(soup).index('<!-- ARTICOL FINAL -->')
  104.                 if begin_comment < str(soup).index(str(p)) < end_comment:
  105.                     recursively_translate(p)
  106.  
  107.             for p in soup.findAll('p', class_='text_obisnuit2'):
  108.                 begin_comment = str(soup).index('<!-- ARTICOL START -->')
  109.                 end_comment = str(soup).index('<!-- ARTICOL FINAL -->')
  110.                 if begin_comment < str(soup).index(str(p)) < end_comment:
  111.                     recursively_translate(p)
  112.  
  113.             for span in soup.findAll('span', class_='text_obisnuit2'):
  114.                 begin_comment = str(soup).index('<!-- ARTICOL START -->')
  115.                 end_comment = str(soup).index('<!-- ARTICOL FINAL -->')
  116.                 if begin_comment < str(soup).index(str(span)) < end_comment:
  117.                     recursively_translate(span)
  118.  
  119.             for li in soup.findAll('li', class_='text_obisnuit'):
  120.                 begin_comment = str(soup).index('<!-- ARTICOL START -->')
  121.                 end_comment = str(soup).index('<!-- ARTICOL FINAL -->')
  122.                 if begin_comment < str(soup).index(str(li)) < end_comment:
  123.                     recursively_translate(li)
  124.  
  125.             for a in soup.findAll('a', class_='linkMare'):
  126.                 begin_comment = str(soup).index('<!-- ARTICOL START -->')
  127.                 end_comment = str(soup).index('<!-- ARTICOL FINAL -->')
  128.                 if begin_comment < str(soup).index(str(a)) < end_comment:
  129.                     recursively_translate(a)
  130.  
  131.             for h4 in soup.findAll('h4', class_='text_obisnuit2'):
  132.                 begin_comment = str(soup).index('<!-- ARTICOL START -->')
  133.                 end_comment = str(soup).index('<!-- ARTICOL FINAL -->')
  134.                 if begin_comment < str(soup).index(str(h4)) < end_comment:
  135.                     recursively_translate(h4)
  136.  
  137.             for h5 in soup.findAll('h5', class_='text_obisnuit2'):
  138.                 begin_comment = str(soup).index('<!-- ARTICOL START -->')
  139.                 end_comment = str(soup).index('<!-- ARTICOL FINAL -->')
  140.                 if begin_comment < str(soup).index(str(h5)) < end_comment:
  141.                     recursively_translate(h5)
  142.  
  143.             for h1 in soup.findAll('h1', {'itemprop':'name'}, class_='den_webinar'):
  144.                 begin_comment = str(soup).index('<!-- ARTICOL START -->')
  145.                 end_comment = str(soup).index('<!-- ARTICOL FINAL -->')
  146.                 if begin_comment < str(soup).index(str(h1)) < end_comment:
  147.                     recursively_translate(h1)
  148.  
  149.         print(f'{filename} translated')
  150.         soup = soup.encode(formatter=UnsortedAttributes()).decode('utf-8')
  151.         new_filename = f'{filename.split(".")[0]}_{destination_language}.html'
  152.         if use_translate_folder:
  153.             try:
  154.                 with open(os.path.join(files_from_folder+r'\translated', new_filename), 'w', encoding='utf-8') as new_html:
  155.                     new_html.write(soup[5:-6])
  156.             except:
  157.                 os.mkdir(files_from_folder+r'\translated')
  158.                 with open(os.path.join(files_from_folder+r'\translated', new_filename), 'w', encoding='utf-8') as new_html:
  159.                     new_html.write(soup[5:-6])
  160.         else:
  161.             with open(os.path.join(files_from_folder, new_filename), 'w', encoding='utf-8') as html:
  162.                 html.write(soup[5:-6])
  163.  
Advertisement
Add Comment
Please, Sign In to add comment