python爬虫实现中英翻译词典

yipeiwu_com6年前Python爬虫

本文实例为大家分享了python爬虫实现中英翻译词典的具体代码,供大家参考,具体内容如下

通过根据某平台的翻译资源,提取出翻译信息,并展示出来,包括输入,翻译,输出三个过程,主要利用python语言实现(python3.6),抓取信息展示。

import urllib.request
import urllib.parse
import json

def en_zh(content):
  url = 'http://fanyi.baidu.com/v2transapi'
  head = {}
  head['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
  
  data={}
  data['from'] = 'en'
  data['to'] = 'zh'
  data['query'] = content
  data['transtype'] = 'translang'
  data['simple_means_flag'] = '3'
  data = urllib.parse.urlencode(data).encode('utf-8')

  req =urllib.request.Request(url,data,head)
  response=urllib.request.urlopen(req)

  html = response.read().decode('utf-8')

  target = json.loads(html)
  print("翻译结果:%s" %(target['trans_result']['data'][0]['dst']))
def zh_en(content):

  url = 'http://fanyi.baidu.com/v2transapi'
  data={}
  data['from'] = 'zh'
  data['to'] = 'en'
  data['query'] = content
  data['transtype'] = 'translang'
  data['simple_means_flag'] = '3'
  data = urllib.parse.urlencode(data).encode('utf-8')

  req =urllib.request.Request(url,data)
  req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36')
  response=urllib.request.urlopen(req)

  html = response.read().decode('utf-8')
  target = json.loads(html)
  print("翻译结果:%s" %(target['trans_result']['data'][0]['dst']))

while(True):
  content = input("请输入要翻译的内容(按q退出):")
  if content=='q':
    input("您已退出,欢迎再次使用")
    break

  en_zh(content) 
  zh_en(content)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python爬虫实例爬取网站搞笑段子

众所周知,python是写爬虫的利器,今天作者用python写一个小爬虫爬下一个段子网站的众多段子。 目标段子网站为“http://ishuo.cn/”,我们先分析其下段子的所在子页的u...

如何准确判断请求是搜索引擎爬虫(蜘蛛)发出的请求

如何准确判断请求是搜索引擎爬虫(蜘蛛)发出的请求

网站经常会被各种爬虫光顾,有的是搜索引擎爬虫,有的不是,通常情况下这些爬虫都有UserAgent,而我们知道UserAgent是可以伪装的,UserAgent的本质是Http请求头中的一...

python爬虫实战之爬取京东商城实例教程

python爬虫实战之爬取京东商城实例教程

前言 本文主要介绍的是利用python爬取京东商城的方法,文中介绍的非常详细,下面话不多说了,来看看详细的介绍吧。 主要工具 scrapy BeautifulSoup r...

Python selenium抓取微博内容的示例代码

Python selenium抓取微博内容的示例代码

Selenium简介与安装 Selenium是什么? Selenium也是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持...

python使用mitmproxy抓取浏览器请求的方法

最近要写一款基于被动式的漏洞扫描器,因为被动式是将我们在浏览器浏览的时候所发出的请求进行捕获,然后交给扫描器进行处理,本来打算自己写这个代理的,但是因为考虑到需要抓取https,所以最后...