This article, in conjunction with the previous article, "Python uses Youdao translation to achieve the" language translator "function" of the implementation code, processing, to achieve the request server to hide user-agent.
There are two general ways that Python implements hidden user-agent:
(1) Before the request object is generated (req in the example below), a dictionary-type head is passed into the urllib.request.Request (URL, data, head) as a parameter;
(2) After the request object is generated (req in the example below), it is implemented by the Add_header () method.
Importurllib.requestImportUrllib.parseImportJSON whiletrue:content= Input ('Please enter what you want to translate (exit input q):') ifContent = ='Q': Break Else: URL='http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc& sessionfrom=http://www.youdao.com/' #head = {} #head[' user-agent ' = ' mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/37.0.2062.124 safari/537.36 'Data={} data['type'] ='AUTO'data['I'] =content data['DOCTYPE'] ='JSON'data['xmlversion'] ='1.8'data['Keyfrom'] ='Fanyi.web'data['UE'] ='UTF-8'data['Action'] ='Fy_by_clickbutton'data['Typoresult'] ='true'Data= Urllib.parse.urlencode (data). Encode ('Utf-8') #req = urllib.request.Request (URL, data, head)req =urllib.request.Request (URL, data) Req.add_header ('user-agent','mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/37.0.2062.124 safari/537.31') Response=Urllib.request.urlopen (req) HTML= Response.read (). Decode ('Utf-8') Target=json.loads (HTML)Print('result of translation:%s'% target['Translateresult'][0][0]['TGT'])
>>> Please enter what you need to translate (exit input Q): Charlton translation results: Charlton Please enter the content to be translated (exit input q): Q>>> req.headers{ ' user-agent ' ' mozilla/5.0 (Windows NT 6.1; WOW64) applewebkit/537.36 (khtml, like Gecko) chrome/37.0.2062.124 safari/537.31'}
We can check whether User-agent is hidden successfully through Req.headers.
Note: The line of code commented above is the implementation of the first method.
How Python hides user-agent when requesting a server