Python Requests URL with Unicode Parameters

后端 未结 3 2116
闹比i
闹比i 2021-01-06 07:25

I\'m currently trying to hit the google tts url, http://translate.google.com/translate_tts with japanese characters and phrases in python using the requests library.

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-06 08:18

    Setting the User-Agent to Mozilla/5.0 fixes this issue.

    from StringIO import StringIO
    import urllib
    import requests
    
    __author__ = 'jacob'
    
    langs = {'japanese': 'ja',
             'english': 'en'}
    
    def get_sound_file_for_text(text, download=False, lang='japanese'):
    
        r = StringIO()
        glang = langs[lang]
        text = text.replace('*', '')
        text = text.replace('/', '')
        text = text.replace('x', '')
        url = 'http://translate.google.com/translate_tts'
        if download:
            result = requests.get(url, params={'tl': glang, 'q': text}, headers={'User-Agent': 'Mozilla/5.0'})
            r.write(result.content)
            r.seek(0)
            return r
        else:
            return url
    

提交回复
热议问题