【Python】如何把某网页上特定的img标签对应的图片下载到本地

【需求】

在某网页上有一批靓图,其特征是img标签,类名是aligncenter,文件扩展名是.jpg,现需要把这批网络图片通过python下载下来。

【代码】

#encoding=utf-8

# 内置网络访问包
import requests

# 内置的urllib.request模块
import urllib.request

# 解析html的BeautifulSoup包,安装方法是pip install BeautifulSoup4
from bs4 import BeautifulSoup

# 引入正则表达式包
import re

# 把请求伪装成浏览器Mozilla
user_agent='Mozilla/4.0 (compatible;MEIE 5.5;windows NT)'
headers={'User-Agent':user_agent}

# 请求地址
url="https://www.zhainq.com/%e7%be%8e%e5%a5%b3%e5%86%99%e7%9c%9f%e6%9c%ba%e6%9e%84/%e6%97%a5%e6%9c%ac%e7%be%8e%e5%a5%b3%e5%86%99%e7%9c%9f/109012.html/16"

# 发起请求获取其html内容
html=requests.get(url,headers=headers)
#print(html.text)

# 使用BeautifulSoup解析html文本
soup= BeautifulSoup(html.text,'html.parser');

# 准备一个列表,用以放入文件名和地址组成的字典
jpglist=[]
# 查找html文本中img标签,指定其class是aligncenter,这个规律需要自己看网页源码探究出来!
for img in soup.find_all('img',class_="aligncenter"):
    # 获取img的实际地址
    addr=img.get("src")

    # 使用正则表达式劈分文本
    parts = re.split(r'[/]', addr)

    # 最后一项即文件名
    filename=parts[-1]

    # 因为此法获取的文件名有两种:png和jpg,png是不需要的,故过滤掉
    if filename.endswith(".jpg"):
        # 准备字典,字典中包含地址和文件名两项
        dic={}
        dic['address']=addr
        dic['filename']=filename
        jpglist.append(dic)

# 遍历列表,其中每一项是个字典
for dic in jpglist:
    #print(dic['filename']+"_"+dic['address'])
    with urllib.request.urlopen(dic['address']) as response:
        data=response.read()
        filename=dic['filename']

        # write binary file
        with open(filename,'wb') as f:
            f.write(data)
            print("download "+filename+" completed.")

print("download successfully!")

END

posted @ 2020-09-20 08:50  不朽的飞翔  阅读(131)  评论(0编辑  收藏  举报