import http.client
import hashlib
import json
import urllib
import random
from openpyxl import load_workbook
import time
wb = load_workbook("W036W评语与退货率.xlsx")
ws = wb["Sheet1"]
qlist=[]
for cell in list(ws.columns)[4]:
c=cell.value
qlist.append(c)
appid = ''
secretKey = ''
httpClient = None
myurl = '/api/trans/vip/translate'
for q in qlist:
fromLang = 'auto' # 源语言
toLang = 'zh' # 翻译后的语言
salt = random.randint(32768, 65536)
sign = appid + q + str(salt) + secretKey
sign = hashlib.md5(sign.encode()).hexdigest()
myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(
q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(
salt) + '&sign=' + sign
try:
httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
httpClient.request('GET', myurl)# response是HTTPResponse对象
response = httpClient.getresponse()
jsonResponse = response.read().decode("utf-8")# 获得返回的结果,结果为json格式
js = json.loads(jsonResponse) # 将json格式的结果转换字典结构
dst = str(js["trans_result"][0]["dst"]) # 取得翻译后的文本结果
print(dst) # 打印结果
except Exception as e:
print(e)
finally:
if httpClient:
httpClient.close()
time.sleep( 2 )
一共89条数据,前面的可以翻译出来,因为我写的是循环,一定数量之后就会返回Expecting value: line 1 column 1 (char 0)。但是我把表格里前面的数据删掉一些就可以全部输出,不知道为什么。
又尝试了一下发现是70条之后的就会返回Expecting value: line 1 column 1 (char 0)。jsonResponse返回的是空值,我拆成两个list做循环都不行。等下找个账号试试别的看行不行