urllib2添加data和header的代碼

#!/usr/bin/env python n# -*- coding: utf-8 -*-nimport urllib,urllib2nimport jsonnimport timenimport randomnimport hashlibnnuser_agent = Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)# 將user_agent寫入頭信息nheaders = { User-Agent : user_agent }nnurl = http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugcnncontent = "I love china"nnsalt = str(time.time()*1000 + random.randint(0,9))nb = "fanyideskweb"nc = "rY0D^0nM0}g5Mm1z%1G4"nsign = hashlib.md5((b+content.decode("GBK")+salt+c).encode(utf-8)).hexdigest()nnurl = http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rulenndata = {}ndata[i] = contentndata[from] = AUTOndata[to] = AUTOndata[smartresult] = dictndata[client] = fanyideskwebndata[salt] = saltndata[sign] = signndata[doctype] = jsonndata[version] = 2.1ndata[keyfrom] = fanyi.webndata[action] = FY_BY_CLICKBUTTIONndata[typoResult] = truenndata = urllib.urlencode(data)nreq = urllib2.Request(url,data,headers) nresponse = urllib2.urlopen(req) nthe_page = response.read()ntarget = json.loads(the_page)nprint u"翻譯結果:" + target[translateResult][0][0][tgt]n

執行結果(IDLE中):

>>> n======== RESTART: D:/Personal/Desktop/python.test/小甲魚/url2test.py ========n翻譯結果:我愛中國n>>> n

推薦閱讀:

第三章 Python讀取PDF內容
python with提前退出:坑與解決方案
Python數據分析學習路徑圖(120天Get新技能)

TAG:Python | 爬虫计算机网络 |