python发送数据包获取返回数据(其他的语言能实现也可以)

2025-04-05 05:44:33
推荐回答(1个)
回答1:

使用百度翻译的一个例子,可以翻译你输入的文字,发送需要的内容,获取返回的数据

import urllib.request
import urllib.parse
import json
import time

while True:
url = 'http://fanyi.baidu.com/v2transapi'

words = input("输入你想翻译的内容:")

data = {}
data['from'] = 'auto'
data['to'] = 'auto'
data['query'] = words
data['transtype'] = 'translang'
data['simple_means_flag'] = '3'

data = urllib.parse.urlencode(data).encode('utf-8')

headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36'
}

req = urllib.request.Request(url, data, headers)
req.add_header('Referer', 'http://fanyi.baidu.com/')
response = urllib.request.urlopen(req)
html = response.read().decode('utf-8')
js = json.loads(html)
# print(html)
# print(js)
print(js['trans_result']['data'][0]['dst'])
time.sleep(1)