urllib模块通过post请求获取数据
功能: 输入你要查找的单词,会返回相对应的结果
import urllib.request import urllib.parse import json class youdaoSpider: def __init__(self): # 注意,这里http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule # 要把连接中的_o去掉,要不然会报{"errorCode":50}错误 self.url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule" self.headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36"} def getData(self, data): # post请求就要传入data rep = urllib.request.Request(self.url, data=data, headers=self.headers) # 发送请求 res = urllib.request.urlopen(rep) # 获取html文本 html = res.read().decode("utf-8") # 将json字符串转换成字典 dic = json.loads(html) # 提取数据 result = dic["translateResult"][0][0]["tgt"] print(result) def workOn(self): work = input("请输入要翻译的单词:") # 上传的数据以字典的形式上传 data = { "i":work , "from": "AUTO", "to": "AUTO", "smartresult": "dict", "client": "fanyideskweb", "salt": "1542875948524", "sign": "3535bd742994f3b74924927dabf24541", "doctype": "json", "version": "2.1", "keyfrom": "fanyi.web", "action": "FY_BY_REALTIME", "typoResult": "false", } # urlencode("字典") - > 字符串 data = urllib.parse.urlencode(data).encode("utf-8") self.getData(data) if __name__ == "__main__": youdao = youdaoSpider() youdao.workOn()
运行结果:
请输入要翻译的单词:hello
你好