python爬虫下载网站所有文件

本文介绍了一种利用Python和正则表达式抓取并下载指定网站上所有资源的方法。通过递归方式遍历网站链接,实现对目标站点内文件的全面下载。适用于对特定网站内容进行批量获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

核心思路是使用正则表达式对网页的html5中的路径名和文件名进行抓取,

然后对路径继续进行同样的抓取,用递归的方式进行搜索。最后把网站上的内容文件全部下载下来



import urllib

import sys
import BeautifulSoup
import re
import os

path = []

def extract(url):
    content = urllib.urlopen(url).read()
    #reg = r'(?:href|HREF)="?((?:http://)?.+?\.txt)'    
    reg = r'<a href="(.*)">.*'
    url_re = re.compile(reg)
    url_lst = re.findall(url_re, content)

    for lst in url_lst:
        ext = lst.split('.')[-1]
    
        if ext[-1] == '/':
           newUrl = url + lst
           extract(newUrl)
        else:
            path.append(url + lst)
       


print "downloading with urllib"
url = 'http://139.196.233.65/js/'
extract(url)

filePath = 'E:/6-学习文档/91-JS/Download/js'
filePath = unicode(filePath, 'utf8')

for p in path:
    fileTitle = p.split('/js')[-1]
    file = filePath + fileTitle
    dir = os.path.dirname(file)
    isExists=os.path.exists(dir)

    if isExists == False:
        os.makedirs(dir)
    urllib.urlretrieve(p, file)






#for lst in url_lst:
#    file = filePath + lst
#    lst = url + '/' + lst
#    urllib.urlretrieve(lst, file)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值