你可以使用 requests 库来发送 POST 请求,并使用 BeautifulSoup 库来解析返回的 HTML 页面。下面是一个用于处理 POST 请求的示例程序:

import requests
from bs4 import BeautifulSoup

def translate_word(word):
    url = 'https://fanyi.baidu.com/v2transapi'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
        'Referer': 'https://fanyi.baidu.com/',
        'Origin': 'https://fanyi.baidu.com',
        'Host': 'fanyi.baidu.com',
        'Accept-Language': 'en-US,en;q=0.9',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'X-Requested-With': 'XMLHttpRequest'
    }

    data = {
        'from': 'en',
        'to': 'zh',
        'query': word,
        'transtype': 'realtime',
        'simple_means_flag': '3'
    }

    response = requests.post(url, headers=headers, data=data)
    json_data = response.json()
    translations = json_data['trans_result']['data']
    
    for translation in translations:
        print(translation['dst'])
        
word = input('请输入您要输入的单词:')
translate_word(word)

请注意,这个示例程序使用了百度翻译网站的 API,但是具体的 URL 和请求头可能会随着网站的更新而改变,所以请确保这些信息是最新的。此外,为了避免被网站识别为机器人,你可能需要定期更新请求头中的 User-Agent 信息。

Python 百度翻译:使用 POST 请求获取单词翻译

原文地址: https://www.cveoy.top/t/topic/pgXR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录