Description
1. Import three modules, Urllib.request.urlopen is used to open the URL link, urllib.parse the UrlEncode method to convert the data object in the browser network to the second parameter of Urlopen data,json.loads () method to convert the string returned by Response.read to JSON format.
2. The data object is all the attributes in the bottom formdata of the headers in the translate from the review element's network.
3. The data in Urlopen (Url,data) is encode encoded into utf-8, and the result after the return value is decode decoded back to Utf-8.
1 Importurllib.request2 ImportUrllib.parse3 ImportJSON4 5Userinput =""6 whileUserinput! ="Exit":7Userinput = input ("Enter the words you want to translate (exit exits):")8URL ="http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc& Sessionfrom=https://www.baidu.com/link"9data = {}Tendata["type"] ="AUTO" Onedata["I"] =Userinput Adata["DOCTYPE"] ="JSON" -data["xmlversion"] ="1.8" -data["Keyfrom"] ="Fanyi.web" thedata["UE"] ="UTF-8" -data["Action"] ="Fy_by_clickbutton" -data["Typoresult"] ="true" -data = Urllib.parse.urlencode (data). Encode ("Utf-8") +Response =Urllib.request.urlopen (url,data) -result = Response.read (). Decode ("Utf-8") +result =json.loads (Result) Aresult = result["Translateresult"][0][0]["TGT"] at Print(Result)
Python Learning Notes (6)--Youdao translation crawler