Python利用爬虫技术实现一个简洁单词翻译程序
import requests
from bs4 import BeautifulSoup
def get_translation(word):
url = 'https://www.ldoceonline.com/dictionary/' + word.lower()
response = requests.get(url)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
pronunciation = soup.find('span', class_='pron').text.strip()
definition = soup.find('div', class_='def-block').text.strip()
return f"Pronunciation: {pronunciation}\nDefinition: {definition}"
else:
return "Word not found in the dictionary."
# 示例使用
word = 'example'
translation = get_translation(word)
print(translation)
这段代码使用了requests库来发送HTTP请求,以及BeautifulSoup库来解析HTML内容。函数get_translation
接收一个单词作为参数,并构造一个查询URL。然后,它发送请求,如果单词存在于词典中,它会解析页面以提取发音和定义,并返回格式化的字符串。如果单词未找到,它会返回一条错误消息。
评论已关闭