Home >  > 小甲鱼爬虫视频教程53、54笔记

小甲鱼爬虫视频教程53、54笔记

0

第53课:

Python 3.x的urllib实际上是将python2.X的urllib,urllib2合并成一个包。

urllib实际上是一个包,包含以下四个模块:

urllib.request
urllib.error
urllib.parse
urllib.robotparser

1import urllib.request
2response = urllib.request.urlopen("http://www.fishc.com")
3html= response.read()
4print(html)  //显示的是二进制的数据
5 
6 
7html=html.decode('UTF-8')
8print(html)

不过第一次执行urllib.request.urlopen的时候,老是出现“ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host”的错误,不过第二天运行的时候又好了。

第54课:

下载猫咪图片的代码:

1import urllib.request
2 
3response = urllib.request.urlopen("http://www.tangshifushi.com/myimg/meitu_2336.jpg")
4cat_img = response.read()
5 
6with open('cat_200_300.jpg','wb') as f:
7    f.write(cat_img)

也可以写成:

1import urllib.request
2 
3req = urllib.requet.Request("http://placekitten.com/g/200/300") //实例化这个request类
4 
5response = urllib.request.urlopen(req)  //urlopen函数的url参数,即可以是string, 也可以是一个request对象。
6cat_img = response.read()
7 
8with open('cat_200_300.jpg','wb') as f:
9    f.write(cat_img)

小甲鱼写的调用有道api进行翻译的代码(PY3.X):不过只能翻译英文,不能翻译中文。

1import urllib.request
2import re 
3import json 
4   
5class Youdao: 
6    def __init__(self): 
7        self.url = 'http://fanyi.youdao.com/openapi.do' 
8        self.key = '695028818' #有道API key 
9        self.keyfrom = 'nicomochina' #有道keyfrom 
10   
11    def get_translation(self,words): 
12        url = self.url + '?keyfrom=' + self.keyfrom + '&key='+self.key + '&type=data&doctype=json&version=1.1&q=' + words
13        page = urllib.request.urlopen(url)
14        result = page.read().decode("utf8")
15        json_result = json.loads(result) 
16        json_result = json_result["translation"
17        for i in json_result: 
18            print(i) 
19   
20youdao = Youdao() 
21while True:
22    msg = input('请输入单词\句子(输入quit结束):'
23    if msg == 'quit'
24        break 
25    youdao.get_translation(msg)

原载:蜗牛博客
网址:http://www.snailtoday.com
尊重版权,转载时务必以链接形式注明作者和原始出处及本声明。

暧昧帖

本文暂无标签

发表评论

*

*