Python爬网站图片、CSS文件和JS文件-最后,输出下载完毕的提示信息,并使用input函数等待用户按回车键退出程序。

import os
import requests
from bs4 import BeautifulSoup

# 获取页面的HTML
url = input("请输入要下载的网址: ")  # 

response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# 下载图片
images = soup.find_all('img')
for img in images:
    image_url = img.attrs.get('src')
    if not image_url:
        continue
    if not image_url.startswith('http'):
        image_url = url + image_url
    
    response = requests.get(image_url)
    with open(os.path.basename(image_url), 'wb') as f:
        f.write(response.content)

# 下载CSS文件
css_files = soup.find_all('link', {'rel': 'stylesheet'})
for css_file in css_files:
    css_url = css_file.attrs.get('href')
    if not css_url:
        continue
    if not css_url.startswith('http'):
        css_url = url + css_url

    response = requests.get(css_url)
    with open(os.path.basename(css_url), 'wb') as f:
        f.write(response.content)

# 下载JS文件
scripts = soup.find_all('script')
for script in scripts:
    js_url = script.attrs.get('src')
    if not js_url:
        continue
    if not js_url.startswith('http'):
        js_url = url + js_url

    response = requests.get(js_url)
    with open(os.path.basename(js_url), 'wb') as f:
        f.write(response.content)

原创 蓝胖子之家 蓝胖子之家

上一篇:037_基于php在线租房管理系统


下一篇:问题