python爬蟲百度翻譯

來源:互聯網
上載者:User

標籤:else   結果   pre   運行   input   user   pos   nic   scribe   

  • python3,爬取的是百度翻譯手機版的網頁
  • 運用requests,json模組
  • 英漢互譯,運行結果

#!/bin/python3# -*- coding: UTF-8 -*-#=============================================#describe:an en to zh and zh to en translater#version:1#update:2018-08-03#---#author:unihon#E-mail:[email protected]#github:https://github.com/unihon#=============================================import requestsimport jsondef trans():    userAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1"        header = {            "Host": "fanyi.baidu.com",            "Origin": "http://fanyi.baidu.com",            "User-Agent": userAgent            }    postUrl="http://fanyi.baidu.com/basetrans"    wd = input("please input a word: ")    print(‘-------------------------------‘)    if wd == ‘‘:        trans()        return        for c in wd:        if c < u‘\u4e00‘ or c > u‘\u9fa5‘:            print(‘[en to zh]\n‘)            mdata = {                    "from":"en",                    "to":"zh",                    "query" : wd                    }            break        elif c == wd[-1]:            print(‘[zh to en]\n‘)            mdata = {                    "from":"zh",                    "to":"en",                    "query" : wd                    }    try:        response = requests.post(postUrl, data = mdata, headers = header)    except:        print(‘connect error!‘)        return 1    result = response.text    result=json.loads(result)        if len(result["dict"]) == 0:        print(‘is null‘)    else:        try:            for i in result["dict"]["word_means"]:                print(‘> ‘+ i)        except KeyError:            print(‘key is null‘)if __name__ == "__main__":    print("===============================")    trans()    print("===============================")
  • 小結

需要注意的是,爬到的json資料,中文一般是unicode編碼的形式,可以用json模組處理。

python爬蟲百度翻譯

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.