百度翻译 Excel Table

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 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!