本文目的:使用python 实现翻译效果
思路:有道翻译可以直接翻译内容,观察它的网页内容以及URL可以发现,它的基本url 和将要翻译的内容组合起来就是最后翻译的页面
比如: 有道中英文翻译的网址是:http://dict.youdao.com/
将要翻译的内容是: I‘m a Chinese
点击一下翻译,然后出现的含有翻译结果页面的地址是: http://dict.youdao.com/w/eng/I‘m%20a%20chinese/#keyfrom=dict2.index
虽然这个网址后面跟了“#keyfrom=dict2.index” 但是不影响
直接访问 http://dict.youdao.com/w/eng/I‘m%20a%20chinese 也能看到翻译结果
因此总体思路如下:
1.获取将要翻译的内容
2.将翻译的内容和有道翻译网址组成新的url
3.获取这个url的页面内容
4.根据这个页面内容获取翻译结果
代码如下:
#!/usr/bin/python #coding:utf-8 import HTMLParser import urllib2 import re import sys reload(sys) sys.setdefaultencoding( "utf-8" ) class BaiduFanyi: def __init__(self,url): self.url=url def get_html_Pages(self,url): try: headers = {‘User-Agent‘:‘Mozilla/5.0 (Windows NT 6.2; rv:16.0) Gecko/20100101 Firefox/16.0‘} #构建请求的request request=urllib2.Request(url,headers=headers) #利用urlopen获取页面代码 response=urllib2.urlopen(request) #将页面转化为UTF-8编码格式 html=response.read().decode(‘utf-8‘) html=HTMLParser.HTMLParser().unescape(html)#处理网页内容, 可以将一些html类型的符号如" 转换回双引号 return html #捕捉异常,防止程序直接死掉 except urllib2.URLError,e: print u"连接失败,错误原因",e.reason return None except urllib2.HTTPError,e: print u"连接失败,错误原因:%s " % e.code return None def get_finally_result(self,html): result_pattern=re.compile(‘<div class="trans-container".*?<p>.*?<p>(.*?)</p>.*?</div>‘,re.S) result=re.search(result_pattern,html) trans_result= result.group(1) return trans_result def run(self): html=self.get_html_Pages(self.url) self.get_finally_result(html) if __name__ == ‘__main__‘: author_content=‘‘‘ ***************************************************** welcome to spider of baidufanyi modify on 2017-05-11 @author: Jimy_Fengqi http://blog.csdn.net/qiqiyingse?viewmode=contents ***************************************************** ‘‘‘ print author_content keywords=raw_input(‘please input the sentence that need translate:‘) if not keywords: keywords="I‘m a Chinese" base_url=‘http://www.youdao.com/w/eng/%s‘ % (keywords) print base_url mybaidufanyi=BaiduFanyi(base_url) mybaidufanyi.run()
时间: 2024-07-30 17:20:39