利用urllib,正则表达式,文件读写,爬取慕课网首页图片
from urllib import request, parse, error
import re # 目前是先写代码,再导入需要的模块
import os
url = 'http://www.imooc.com/' # 慕课网首页
with request.urlopen(url) as response:
# response.read() 返回 bytes 类型,需要转换为 str 进行正则
html_page = response.read().decode('utf-8')
# r'http://.+\.jpg' 会匹配到其他信息
img = re.compile(r'http://**[\.\d\-a-zA-Z\/\s]**+\.jpg')
img_urls = re.findall(img,html_page)
补写 re.findall() 的知识
i = 0
for url in img_urls:
i += 1
try:
with open(str(i)+'.jpg','wb') as f: # open(file_name,'wb') 以二进制形式打开图片
with request.urlopen(url,timeout = 3) as req_url:
img_buf = req_url.read() # .decode('utf-8')
f.write(img_buf)
print('No. %d.jpg is downloaded!' % i)
except error.URLError as e:
print('something is wrong!')
os.remove(str(i)+'.jpg')
i -= 1
这里只爬取了一个页面的图片,还可以对多个页面进行爬取。
没有进行模块化