爬取网页及内部静态资源python版

修改文件保存路径(如果有必要的话)


# -*- coding: utf-8 -*-
"""
Created on Tue Jun 14 09:57:31 2022

@author: kankan_ol(冰原狼)
"""

from urllib.request import urlopen
import re
import os
import requests

# 文件路径保存路径 没有创建
savePath = "D:/apro/apythondata"
if not os.path.exists(savePath):
    os.makedirs(savePath)

# 待爬取网站域名
baseUrl = "https://xxx.xxx.com"

# 静态页面地址
url = "https://xxx.xxx.com/xxx/index.html"
myURL = urlopen(url)

# 打开文件 没有创建
f = open(savePath + "/index.html", "wb")
# 读取文本
content = myURL.read()
# 写入文件
f.write(content)
# 关闭文件流
f.close()

#  获取页面内容
r = requests.get(url)
r.encoding = 'gb2312'
# 正则匹配  文件中连接 js css  路径地址
matchs = re.findall(r"(?<=href=\").+?(?=\")|(?<=href=\').+?(?=\')|(?<=src=\").+?(?=\")|(?<=src=\').+?(?=\')" , r.text)

for path in matchs:
    # 剔除 https 开头的资源
    if "https" not in path:
        href = baseUrl + path
        text = urlopen(href)
        content2 = text.read()
        pp = path.split("?")
        filePath = savePath+pp[0]
        r = '/'
        d = filePath.split('/')
        d2 = d[:len(d)-1]
        dirs = r.join(d2)
        print(dirs)
        # 判断文件地址是否存在,否则创建
        if not os.path.exists(dirs):
            os.makedirs(dirs)
        f1  = open(filePath, "wb")
        f1.write(content2)
        f1.close()

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值