python 批量下载 spring 的 xsd

本文介绍了一个使用Python编写的简单工具,该工具能够自动从Spring官方网站下载对应的XML Schema Definition (XSD) 文件到本地指定目录。通过解析网页源码获取文件链接,并利用urllib模块实现文件下载。
#coding=utf-8

import os
import urllib
import urllib2
import re
from bs4 import BeautifulSoup
# 利用 urllib.urlretrieve() 函数进行下载。非常方便

import socket
#超时时间
socket.setdefaulttimeout(5)

# 一个空文件夹
basedir=r"E:\spring".decode('utf-8')
os.chdir(basedir)
host="http://www.springframework.org"

def getFolderName(url):
    pattern = re.compile(r'.*/(.*)')
    match = pattern.match(url)
    # 返回最后一个 / 后面的字符
    if match:
        return match.group(1)


# 存储spring 的集合
list = ['http://www.springframework.org/schema/beans',
        'http://www.springframework.org/schema/aop',
        'http://www.springframework.org/schema/mvc',
        'http://www.springframework.org/schema/p',
        'http://www.springframework.org/schema/context',
        'http://www.springframework.org/schema/tx'
        ]

# 获取页面中的 文件名称
def getFilesByUrl(url):
    #返回列表
    list=[]
    try:
        html = urllib2.urlopen(url)
    except Exception as err:
        print err
    soup = BeautifulSoup(html,"lxml")
    for link in soup.find_all('a'):
        fileName = link['href']
        if not fileName.startswith('/') and (fileName.endswith('xsd') or fileName.endswith('/')):
            list.append(fileName)
    return list

list = getFilesByUrl("http://www.springframework.org/schema")
print list
for url in list:
    print url[:-1]
    url = "http://www.springframework.org/schema/"+url[:-1]
    folder = getFolderName(url)
    print folder
    if not os.path.exists(folder):
        os.mkdir(folder)
    files = getFilesByUrl(url)
    print files
    for fileName in files:
        try:
            print url+"/"+fileName
            urllib.urlretrieve(url+"/"+fileName,folder+"/"+fileName)
        except Exception as err:
            print err

 

转载于:https://www.cnblogs.com/whm-blog/p/7168224.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值