Python爬虫手把手教程-POST请求爬取数据实战

试了一下,写了个百度翻译的Python脚本
不过后来发现我找到的是SUG也就是suggestion的建议提示词,只支持单词的翻译,如果没有提示词就不显示,但是这个支持中英文互译。
程序运行预览:

百度翻译中提示词的预览:

代码:
import requests
import json
def translateBaidu(kw):
# 请求URL
url = "https://fanyi.baidu.com/sug"
data = {
'kw': kw
}
try:
res = requests.post(url=url, data=data)
res.raise_for_status()
# 检查请求是否成功,如果状态码不是 200,抛出异常
except requests.exceptions.RequestException as e:
print("请求失败:", e)
return
try:
result = res.json()
r_str = str(res.json()).replace("\'", "\"")
r_dict = json.loads(r_str)
for item in r_dict['data']:
if item['v']:
print(item['v'])
else:
print("Error:遍历出现问题")
except (json.JSONDecodeError, KeyError) as e:
print(res.json())
print("解析结果出错:", e)
# 主程序入口
if __name__ == "__main__":
while True:
keys = input("请输入翻译的文本:")
if keys == 'q':
break
translateBaidu(keys)