第53课:
Python 3.x的urllib实际上是将python2.X的urllib,urllib2合并成一个包。
urllib实际上是一个包,包含以下四个模块:
urllib.request
urllib.error
urllib.parse
urllib.robotparser
import urllib.request
response = urllib.request.urlopen("http://www.fishc.com")
html= response.read()
print(html) //显示的是二进制的数据
html=html.decode('UTF-8')
print(html)
不过第一次执行urllib.request.urlopen的时候,老是出现“ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host”的错误,不过第二天运行的时候又好了。
第54课:
下载猫咪图片的代码:
import urllib.request
response = urllib.request.urlopen("http://www.tangshifushi.com/myimg/meitu_2336.jpg")
cat_img = response.read()
with open('cat_200_300.jpg','wb') as f:
f.write(cat_img)
也可以写成:
import urllib.request
req = urllib.requet.Request("http://placekitten.com/g/200/300") //实例化这个request类
response = urllib.request.urlopen(req) //urlopen函数的url参数,即可以是string, 也可以是一个request对象。
cat_img = response.read()
with open('cat_200_300.jpg','wb') as f:
f.write(cat_img)
小甲鱼写的调用有道api进行翻译的代码(PY3.X):不过只能翻译英文,不能翻译中文。
import urllib.request
import re
import json
class Youdao:
def __init__(self):
self.url = 'http://fanyi.youdao.com/openapi.do'
self.key = '695028818' #有道API key
self.keyfrom = 'nicomochina' #有道keyfrom
def get_translation(self,words):
url = self.url + '?keyfrom=' + self.keyfrom + '&key='+self.key + '&type=data&doctype=json&version=1.1&q=' + words
page = urllib.request.urlopen(url)
result = page.read().decode("utf8")
json_result = json.loads(result)
json_result = json_result["translation"]
for i in json_result:
print(i)
youdao = Youdao()
while True:
msg = input('请输入单词\句子(输入quit结束):')
if msg == 'quit':
break
youdao.get_translation(msg)
原载:蜗牛博客
网址:http://www.snailtoday.com
尊重版权,转载时务必以链接形式注明作者和原始出处及本声明。