1. 环境准备
1.1 安装python
1.2 安装pip: easy_install pip
1.3 安装requests库:python -m pip install requests
1.4 eclipse安装pydev插件
2. 过程
主要用到urllib中的request模块,请求目标地址,并将获取到的内容解码成HTML,然后通过正则匹配获取图片的地址,最后通过urlretrieve方法将获取到的图片下载到本地
3. 代码部分
#!/usr/local/bin/python3.6
# encoding: utf-8
from urllib import request
import re
def main():
# 获取网页并解码
response = request.urlopen("https://www.douban.com/photos/album/1652957514/");
html = response.read()
html = html.decode("utf-8")
# 正则匹配图片,获取图片地址的list,正则中()是最终需要匹配返回的内容
reg = '<img\swidth="\d+"\ssrc="(https://img3.doubanio.com[/\w\.]*)'
imgre = re.compile(reg)
imgs = re.findall(imgre, html)
# 将图片下载到本地,由于获取到的某些地址无法访问会有报错,因此此处需要catch一下异常
x=0
for img in imgs:
# print(img)
try:
request.urlretrieve(img, 'C:\work\Python\spider\%s.gif' % x)
# request.urlopen(img)
x += 1
except Exception as e:
print(e)
if __name__ == '__main__':
main()
参考
以上内容只是个人练习记录,参考以下博客,博客内容更加详细
https://blog.csdn.net/cloudox_/article/details/53465923
https://blog.csdn.net/c406495762/article/details/58716886