mouuff / mtranslate

A simple api for google translate
MIT License
286 stars 83 forks source link

Add fake user agent feature #11

Closed leoohermoso closed 6 years ago

leoohermoso commented 7 years ago

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
MIT License
Copyright (c) 2016 Arnaud Aliès
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import re
import sys
from fake_useragent import UserAgent

if (sys.version_info[0] < 3):
    import urllib2
    import urllib
    import HTMLParser
else:
    import html.parser
    import urllib.request
    import urllib.parse

ua = UserAgent()

def unescape(text):
    if (sys.version_info[0] < 3):
        parser = HTMLParser.HTMLParser()
    else:
        parser = html.parser.HTMLParser()
    return (parser.unescape(text))

def translate(to_translate, to_language="auto", from_language="auto"):
    """Returns the translation using google translate
    you must shortcut the language you define
    (French = fr, English = en, Spanish = es, etc...)
    if not defined it will detect it or use english by default
    Example:
    print(translate("salut tu vas bien?", "en"))
    hello you alright?
    """
    base_link = "http://translate.google.com/m?hl=%s&sl=%s&q=%s"
    if (sys.version_info[0] < 3):
        to_translate = urllib.quote_plus(to_translate)
        link = base_link % (to_language, from_language, to_translate)
        request = urllib2.Request(link, headers=getuseragent())
        raw_data = urllib2.urlopen(request).read()
    else:
        to_translate = urllib.parse.quote(to_translate)
        link = base_link % (to_language, from_language, to_translate)
        request = urllib.request.Request(link, headers=getuseragent())
        raw_data = urllib.request.urlopen(request).read()
    data = raw_data.decode("utf-8")
    expr = r'class="t0">(.*?)<'
    re_result = re.findall(expr, data)
    if (len(re_result) == 0):
        result = ""
    else:
        result = unescape(re_result[0])
    return (result)

def getuseragent():
    while True:
        try:
            return {'User-Agent': ua.random.encode()}
        except:
            pass
john-bhat commented 7 years ago

its not working . after getting response for six strings in loop it gives error:

Traceback (most recent call last):

File "", line 17, in main()

File "", line 9, in main translated.append(translate(data.iloc[0:,0][i]))

File "core.py", line 75, in translate re_result = re.findall(expr, data)

File "C:\Users\admin\Anaconda2\lib\urllib2.py", line 154, in urlopen return opener.open(url, data, timeout)

File "C:\Users\admin\Anaconda2\lib\urllib2.py", line 435, in open response = meth(req, response)

File "C:\Users\admin\Anaconda2\lib\urllib2.py", line 548, in http_response 'http', request, response, code, msg, hdrs)

File "C:\Users\admin\Anaconda2\lib\urllib2.py", line 473, in error return self._call_chain(*args)

File "C:\Users\admin\Anaconda2\lib\urllib2.py", line 407, in _call_chain result = func(*args)

File "C:\Users\admin\Anaconda2\lib\urllib2.py", line 556, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)

HTTPError: Forbidden

mouuff commented 6 years ago

Don't make this pull request in legacy branch, also don't paste your code in the comments its hardly readable, Fell free to make another pull request, I m closing this one Thank you for your interest on that project