详细可以见我的个人博客:本地HTML中图片下载
单个文件中所有图片下载
import requests
from lxml import etree
import os
本地html文件读取到内存
这里需要注意下编码方式!
with open('爬虫与API(上).html','r',encoding = 'utf-8') as f:
html = f.read()
页面解析
selector = etree.HTML(html)
img_list = selector.xpath('//img/@src')
img_list
['https://pic2.zhimg.com/v2-92e8bf502b2a8cb1c972215297161e40_b.jpg',
'https://pic3.zhimg.com/v2-8a64c355393635e51f486e8f77a31b11_b.jpg',
'https://pic3.zhimg.com/v2-b0b7e8426f7abe8bba55748830e1fedb_b.jpg',
'https://pic3.zhimg.com/v2-1ad5fce7304021d5e8240513242b1842_b.jpg',
'https://pic2.zhimg.com/v2-c4b13d820e724740b6d22d26cd1f78e4_b.jpg']
图片下载
num = 0
for img_url in img_list:
img = requests.get(img_url)
#下面是新建文件夹、图片文件名
num += 1
img_dir = os.getcwd() + '/爬虫与API(上)/'
if not os.path.exists(img_dir):
os.makedirs(img_dir)
file_name = img_dir + str(num) + ".png"
#下面是图片文件的保存