practice之Python爬取百度翻译页面
程序员文章站
2022-05-04 12:05:12
...
1.获取需求
from urllib import request,parse
import json
2.根据需求,寻找网站
url = 'http://fanyi.baidu.com/sug'
3.定义函数传入需要进行翻译的数据,转换为字符串后并将网站数据获取到本地、解析json并打印翻译结果
def translate(kw):
form = {
'kw':kw
}
form_str = parse.urlencode(form)
form_bytes = form_str.encode('utf-8')
response = request.urlopen(url,data = form_bytes)
res_dict = json.loads(response.read().decode('utf-8'))
result = res_dict['data'][0]['v']
return result
4.测试代码
if __name__ == '__main__':
res = translate('篮球')
print(res)
res = translate('足球')
print(res)
6.测试返回的内容
[lán qiú] basketball;
[zú qiú] football; soccer; association football; c
Process finished with exit code 0