1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python爬百度翻译-python爬虫实现百度翻译

python爬百度翻译-python爬虫实现百度翻译

时间:2019-09-02 11:12:00

相关推荐

python爬百度翻译-python爬虫实现百度翻译

简述:

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

实现功能:

百度翻译

思路:

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

环境

python3,urllib模块,json模块

代码:import urllib.request

import urllib.parse

import json

content = input("请输入需要翻译的内容: ")

#百度翻译接口

url = "/sug"

#生成一个字典,传输kw键值

data = urllib.parse.urlencode({"kw": content})

headers = {

'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/0101 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"])

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。