Python爬虫实现百度翻译功能过程详解

2020-09-30 0 365

首先,需要简单的了解一下爬虫,尽可能简单快速的上手,其次,需要了解的是百度的API的接口,搞定这个之后,最后,按照官方给出的demo,然后写自己的一个小程序

打开浏览器 F12 打开百度翻译网页源代码:

Python爬虫实现百度翻译功能过程详解

我们可以轻松的找到百度翻译的请求接口为:http://fanyi.baidu.com/sug

Python爬虫实现百度翻译功能过程详解

然后我们可以从方法为POST的请求中找到参数为:kw:job(job是输入翻译的内容)

Python爬虫实现百度翻译功能过程详解

Python爬虫实现百度翻译功能过程详解

下面是代码部分:

from urllib import request,parse
import json


def translate(content):
  url = \"http://fanyi.baidu.com/sug\"
  data = parse.urlencode({\"kw\":content}) # 将参数进行转码
  headers = {
    \'User-Agent\': \'Opera/9.80 (Android 2.3.4; Linux; Opera Mobi/build-1107180945; U; en-GB) Presto/2.8.149 Version/11.10\'
  }
  req = request.Request(url,data=bytes(data,encoding=\"utf-8\"),headers=headers)
  r = request.urlopen(req)
  # print(r.code) 查看返回的状态码
  html = r.read().decode(\'utf-8\')
  # json格式化
  html = json.loads(html)
  # print(html)
  for k in html[\"data\"]:
    print(k[\"k\"],k[\"v\"])

if __name__ == \'__main__\':
  content = input(\"请输入您要翻译的内容:\")
  translate(content)

结果如下

Python爬虫实现百度翻译功能过程详解

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。

遇见资源网 Python Python爬虫实现百度翻译功能过程详解 http://www.ox520.com/25819.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务