百度翻譯 Excel Table

Python_xiaohe發表於2020-03-23
import requests
import json
import xlrd
from xlutils.copy import copy
from tkinter import filedialog
import time
import os

def translation(filename):
    #Excel的處理過程
    num = 0
    filename_cp = 'result.xls'
    if os.path.exists(filename_cp):
        num+=1
        filename_cp = 'result(' + str(num) + ').xls'
    file = xlrd.open_workbook(filename)
    wb = copy(file)
    sheet_cp = wb.get_sheet(0)
    sheet_rd = file.sheet_by_name('Sheet1')
    nrow = sheet_rd.nrows

    url = "https://fanyi.baidu.com/sug"#???

    for i in range(1,nrow): #range(a,b)不包含a

        value = sheet_rd.cell(i,0).value
        #爬蟲部分
        data = {
            "kw": value,#???
        }
        r = requests.post(url,headers=headers,data=data)
        jsonret = json.loads(r.content.decode())    
        time.sleep(0.5)
        try:
            print(jsonret)
            eng_words = jsonret['data'][0]['v'] # data和v都相當於字典中的鍵值,0是列表中第一個
            print(eng_words)
            sheet_cp.write(i,1,eng_words)
        except:
            next
    wb.save(filename_cp)

headers = {
    'accept':'*/*',
    'accept-encoding':'gzip,deflate,br',
    'accept-language':'zh-CN,zh;q=0.9',
    'content-length':'130',
    'content-type':'application/x-www-form-urlencoded;charset=UTF-8',
    'cookie':'你的cookie',
    'origin':'https://fanyi.baidu.com',
    'referer':'https://fanyi.baidu.com/?aldtype=16047',
    'sec-fetch-dest':'empty',
    'sec-fetch-mode':'cors',
    'sec-fetch-site':'same-origin',
    'user-agent':'Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/80.0.3987.149Safari/537.36',
    'x-requested-with':'XMLHttpRequest',
    }

if __name__=='__main__':
    filename = filedialog.askopenfilename()
    translation(filename)
    print("Done")



本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章