下载某个网页的图片

# from urllib import request
# import requests
# rs =requests.get('http://cnliutz.uicp.io')
# with open('cnliutz.txt','w+',encoding="utf-8") as f:
#     f.write(rs.text)
#     print(f.readlines())
# r = requests.get('https://www.baidu.com/img/bd_logo1.png')
# with open('baidu.png', 'wb') as fp:
#     fp.write(r.content)
from bs4 import BeautifulSoup
import requests
#import re
import os
#import time
#import random
#import urllib.request

def get_html(url):
    try:
        r = requests.get(url, timeout=30)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return "ERROR"  

def get_content(url):
    html = get_html(url)
    soup = BeautifulSoup(html, 'lxml')
    img = soup.find_all('img', class_ = "headerimage") #在网页中,按F12,找到所有的img标签,更改本行class_ = "headerimage",即可下载其他图片 
    return img

def save_img(img):
    for i in img:
        img_url = i['src']
        name = img_url.split('/')[-1]
        with open(name, 'wb') as f:
            img = requests.get(img_url).content
            f.write(img)
            print('正在保存图片:', name)   

def main():
    url = "http://cnliutz.uicp.io"
    img = get_content(url)
    save_img(img) 

if __name__ == '__main__':
    main()
    #url = "http://cnliutz.uicp.io"
    # print(get_html(url))
    print(os.getcwd())


#以上代码win11,python 3.8.5调试通过,请提前安装beautifulsoup4,requests两个库。
pip install beautifulsoup4,requests  -i http://pypi.douban.com/simple