Python 百度翻译 API:使用 requests 和 BeautifulSoup 获取单词翻译
使用 Python 的 requests 库可以发送 POST 请求,并使用 BeautifulSoup 库来解析 HTML 页面。下面是一个示例程序,可以利用百度翻译网站(https://fanyi.baidu.com/)查询某个单词的含义。
import requests
from bs4 import BeautifulSoup
def translate(word):
url = 'https://fanyi.baidu.com/'
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'
}
data = {
'kw': word
}
response = requests.post(url, headers=headers, data=data)
soup = BeautifulSoup(response.text, 'html.parser')
# 解析HTML页面,获取翻译结果
result = soup.find('div', class_='output-bd').find('div', class_='output-bd-inner').text.strip()
return result
if __name__ == '__main__':
word = input('请输入要查询的单词:')
result = translate(word)
print('查询结果:', result)
运行该程序后,会要求用户输入要查询的单词,然后发送 POST 请求到百度翻译网站,解析返回的 HTML 页面,最后输出查询结果。请注意,这个程序只能获取到翻译结果的第一个意思,如果需要获取更多的意思,可以进一步修改代码。
扩展思路:
- 使用正则表达式或更精准的 CSS 选择器,从 HTML 页面中提取所有翻译结果。
- 尝试使用百度翻译 API,获取更完整的翻译信息,包括词性、例句等。
- 考虑处理异常情况,例如网络连接错误、翻译结果为空等。
希望本教程能够帮助您理解如何使用 Python 进行网页数据抓取和解析。
原文地址: https://www.cveoy.top/t/topic/pgXo 著作权归作者所有。请勿转载和采集!