作者:黑暗中的数字 | 来源:互联网 | 2023-05-19 05:22
1.下载一张图片代码1importurllib.requestresponseurllib.request.urlopen(http:photocdn.sohu.com2
1.下载一张图片代码1
import urllib.request
response = urllib.request.urlopen('http://photocdn.sohu.com/20100906/Img274741430.jpg')
image = response.read()
with open('D:\\cat_200_300.jpg','wb') as f: #打开文件
f.write(image) #写入文件
2.下载一张图片代码2
import urllib.request
request = urllib.request.Request('http://photocdn.sohu.com/20100906/Img274741430.jpg')
response = urllib.request.urlopen(request)
image = response.read()
with open('D:\\cat_200_300.jpg','wb') as f:
f.write(image)
3.获取请求的url
> request.get_full_url()
'http://photocdn.sohu.com/20100906/Img274741430.jpg
4.获取响应码
response.getcode()
200
5.获取响应信息
response.info()
>>> print(response.info())
Server: Tengine
Content-Type: image/jpeg
Content-Length: 32052
Connection: close
Date: Wed, 11 Oct 2017 02:59:56 GMT
Last-Modified: Mon, 06 Sep 2010 08:27:47 GMT
Expires: Tue, 09 Jan 2018 02:59:56 GMT
Cache-Control: max-age=7776000
X-RS: 34079416.44499832.45112407
X-RS: 10888362.20063412.11942198
FSS-Cache: MISS from 6562920.11412594.7616690
FSS-Proxy: Powered by 6497640.11281778.7551665
Accept-Ranges: bytes
Via: cache14.l2et15-2[0,200-0,H], cache18.l2et15-2[1,0], cache2.cn869[80,200-0,M], cache9.cn869[81,0]
Age: 7118675
X-Cache: MISS TCP_MISS dirn:-2:-2 mlen:-1
X-Swift-SaveTime: Mon, 01 Jan 2018 12:24:31 GMT
X-Swift-CacheTime: 657325
Timing-Allow-Origin: *
EagleId: 767b029d15148094715568685e
6.访问有道词典查询单词
import urllib.request
import urllib.parse
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
data = {}
data['i'] = 'I love you'
data['type'] = 'AUTO'
data['doctype'] = 'json'
data['version'] = '2.1'
data['keyfrom'] = 'fanyi.web'
data['typoResult'] = 'true'
data = urllib.parse.urlencode(data).encode('utf-8')
response = urllib.request.urlopen(url,data)
html = response.read().decode('utf-8')
print(html)
7.结果json数据
{"type":"EN2ZH_CN","errorCode":0,"elapsedTime":1,"translateResult":[[{"src":"I love you","tgt":"我爱你"}]]}
8.处理查询的数据,将json转化为字典
import json
target = json.loads(html)
{'type': 'EN2ZH_CN', 'errorCode': 0, 'elapsedTime': 1, 'translateResult': [[{'src': 'I love you', 'tgt': '我爱你'}]]}
9.获取翻译的数据
target['translateResult'][0][0]['tgt']
10.有道词典
import urllib.request
import urllib.parse
import json
while True:
text = input('请输入要翻译的文字:')
if text == 'exit':
break
url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
data = {}
data['i'] = text
data['type'] = 'AUTO'
data['doctype'] = 'json'
data['version'] = '2.1'
data['keyfrom'] = 'fanyi.web'
data['typoResult'] = 'true'
data = urllib.parse.urlencode(data).encode('utf-8')
response = urllib.request.urlopen(url,data)
html = response.read().decode('utf-8')
target = json.loads(html)
print(target['translateResult'][0][0]['tgt'])
print('输入exit退出程序!')
'我爱你'
代理