import urllib.request
#urllib.request.urlopen可以传入url或者Request对象
#req=urllib.request.Request("http://placekitten.com/g/500/600")
#response=urllib.request.urlopen(req)
#response的geturl,info(),getcode()得到状态,200表示正常访问
response=urllib.request.urlopen("http://placekitten.com/g/500/600")
cat_img=response.read()
with open(\'cat_500_600.jpg\',\'wb\') as f:
f.write(cat_img)
#get一般从服务器获得数据,也可以用来传表单列表等数据
#post传数据到服务器
import urllib.request
import urllib.parse
import json
content=input("请输入需要翻译的内容:")
url=\'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule\'
data={}
data[\'i\']=content
data[\'from\']=\'AUTO\'
data[\'to\']=\'AUTO\'
data[\'smartresult\']=\'dict\'
data[\'client\']=\'fanyideskweb\'
data[\'salt\']=\'1520575049536\'
data[\'sign\']=\'4514c46c320493ba8c034eaa8d9decaf\'
data[\'doctype\']=\'json\'
data[\'version\']=\'2.1\'
data[\'keyfrom\']=\'fanyi.web\'
data[\'action\']=\'FY_BY_CLICKBUTTION\'
data[\'typoResult\']=\'false\'
data[\'ue\']=\'utf-8\'
#data需要特定的格式,可以用urllib.parse.urlencode()来转成该形式
#encode把unicode编码成utf-8格式
data=urllib.parse.urlencode(data).encode(\'utf-8\')
#urlopen如果穿个data参数,那么以post的格式提交,否则以get的格式提交
response=urllib.request.urlopen(url,data)
#decode是把unicode解码转成utf-8
html=response.read().decode(\'utf-8\')
target=json.loads(html)
print("翻译结果:%s"%target[\'translateResult\'][0][0][\'tgt\'])