网络编程
位置:首页>> 网络编程>> Python编程>> Python爬虫实现百度翻译功能过程详解

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

作者:javascript痴痴  发布时间:2024-01-01 08:02:10 

标签:Python,爬虫,百度,翻译

首先,需要简单的了解一下爬虫,尽可能简单快速的上手,其次,需要了解的是百度的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爬虫实现百度翻译功能过程详解

来源:https://www.cnblogs.com/homehtml/p/12821609.html

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com