使用爬虫来制作一个简单的翻译的东西,翻译的来源是有道,可以实现从英文到中文,也可以从中文到英文。(其实就是爬取了有道的翻译信息)
翻译实例
E:\>python test.py
input the word you want to search:
are
are:
1:v. 是(be的第二人称单复数现在式)
2:n. 公亩
3:n. (Are)人名;(意、西、芬)阿雷
E:\>python test.py
input the word you want to search:
你好
你好:
1:hello;hi
from bs4 import BeautifulSoup
import bs4
import requests
def getHtmlText(url):
try:
r=requests.get(url,timeout=30)
r.raise_for_status()
r.encoding=r.apparent_encoding
return r.text
except:
return ""
def parserPage(html):
result=list()
soup=BeautifulSoup(html,'html.parser')
result=soup.find('div',attrs={'class':'trans-container'}).ul.strings #获取解释的字符串
return result
def printTransResult(word,translist):
print(word+':')
count=0
for tran in translist:
if len(tran)>0:
count+=1
print('%d:%s'%(count,tran))
def main():
keyword=input('input the word you want to search:\n')
url='http://dict.youdao.com/w/'+keyword
html=getHtmlText(url)
tlt=parserPage(html)
tlt=[i for i in tlt if i !='\n']
printTransResult(keyword,tlt)
main()