美文网首页
python爬虫实现百度翻译

python爬虫实现百度翻译

作者: kevinfaith | 来源:发表于2018-09-20 18:43 被阅读12次

简述:

最近在学习python,就开始研究爬虫,写了个简单的程序

实现功能:

百度翻译

思路:

通过浏览器的开发者工具,发现百度翻译的接口和翻译所需要发送的数据包,通过python实现模拟浏览器进行百度翻译的行为

环境

python3,urllib模块,json模块

代码:

import urllib.request
import urllib.parse
import json

content = input("请输入需要翻译的内容:\n")
#百度翻译接口
url = "http://fanyi.baidu.com/sug" 
#生成一个字典,传输kw键值
data = urllib.parse.urlencode({"kw": content})  
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0'
}
#生成Request对象
req = urllib.request.Request(url,data=bytes(data,encoding="utf-8"),headers=headers)
r = urllib.request.urlopen(req)
html = r.read().decode('utf-8')
#解析JSON包
html = json.loads(html)  
for k in html["data"]:
print(k["k"],k["v"])

相关文章

网友评论

      本文标题:python爬虫实现百度翻译

      本文链接:https://www.haomeiwen.com/subject/kkwnnftx.html