目录
▲urllib相比socket能更加简单的处理网页内容,基本处理方式与文件类似
1 读取网页信息
import urllib.request
fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')###打开要访问的网页
for line in fhand:###用for loop逐行读取内容
print(line.decode().strip())
▲一旦使用urllib.urlopen()打开网页,我们可以把它当作一个文件,然后使用for循环来读取它。
▲ 逐行读取时仍然需要decode每行的内容,strip方法去除首尾空格
输出内容:
But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
▲与socket库相比输出内容没有头文件header,并不是传输的时候没有header,而是urllib将其去除了
▲示例:urllib读取网页文本并计数单词数
import urllib.request, urllib.parse, urllib.error
fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')###打开网页文件
counts = dict()###创建空白字典储存单词和数目
for line in fhand:###循环每行
words = line.decode().split()###decode解析line内容,split将line字符串转化为包含每个单词的列表
for word in words:###计数单词数
counts[word] = counts.get(word, 0) + 1
print(counts)
2 读取二进制(非文本)文件(图像,视频等)
▲处理思路:
(1)读入全部内容储存到字符串内
(2)将字符内容储存到本地
与socket不同,上述步骤不需要手动查找并跳过头文件,因为urllib已经帮我们跳过了头文件
import urllib.request, urllib.parse, urllib.error
img = urllib.request.urlopen('http://data.pr4e.org/cover3.jpg').read()###read方法一次性读入全部内容
fhand = open('cover3.jpg', 'wb')###创建本地文件,wb表示以binary格式写入
fhand.write(img)###写入内容
fhand.close()###关闭本地文件
▲当传输内容为很大或者为一个视频时,一次性读入会耗尽内存,因此应该分步读入并转存
import urllib.request, urllib.parse, urllib.error
img = urllib.request.urlopen('http://data.pr4e.org/cover3.jpg')###打开网页
fhand = open('cover3.jpg', 'wb')###创建本地文件
size = 0###用size记录传输的总量
###分布传输和转存内容
while True:
info = img.read(100000)###每次读入100000字符
if len(info) < 1: break###判断传输完毕后退出循环
size = size + len(info)###更新总的传输字符
fhand.write(info)###储存本次传输内容
print(size, 'characters copied.')###输出传输总量
fhand.close()###关闭本地文件
上述代码每次传输100000个 字符并储存到本地,然后重新读入100000个字符,因此不会导致内存耗尽。