• python 爬取网站首页并获取资源文件


    一、使用requests模块,如果没有安装请使用如下命令,安装requests模块

    pip install requests

    二、打开PyCharm,创建一个新的py文件

    1.请求网站,获取网页信息

    首先使用浏览器,获取请求头信息,用于python模拟浏览器行为请求

     封装请求方法

    1. def get_html(url):
    2. """ 请求网址 返回网页内容 """
    3. A = requests.Session()
    4. A.headers = {
    5. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:103.0) Gecko/20100101 Firefox/103.0',
    6. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
    7. }
    8. web = A.get(url, timeout=7)
    9. # 设置解析编码的方式
    10. web.encoding = 'gb2312'
    11. return web

     2.通过re模块来匹配获取相应资源路径,os模块创建文件夹及创建写入文件

    (1)js 路径为src

    (2)image 路径为src

    (3)css 路径为href 但会与a标签的href重复 故要多增加一点字符串以作区分

    代码如下:

    1. def get_all_img(content):
    2. """获取网页所有 img css js"""
    3. # 更换编码方式
    4. content = content.replace('charset=gb2312', 'charset=utf-8')
    5. # 获取所有img js文件路径
    6. f_re = 'src="(.*?)"'
    7. file_paths = re.findall(f_re, content)
    8. # 获取单引号的img js文件路径
    9. f_re2 = "src='(.*?)'"
    10. file2_paths = re.findall(f_re2, content)
    11. # 获取所有css文件路径
    12. c_re = 'type="text/css" href="(.*?)"'
    13. css_paths = re.findall(c_re, content)
    14. # 合并到一个列表中
    15. file_paths.extend(css_paths)
    16. if file2_paths:
    17. file_paths.extend(file2_paths)
    18. for file in file_paths:
    19. # 获取文件链接后缀名 只获取css image文件
    20. file_infos = file.split('/')
    21. fileName = file_infos[len(file_infos) - 1]
    22. fileExts = fileName.split('.')
    23. ext = fileExts[len(fileExts) - 1].strip()
    24. if file.find('.js') > -1:
    25. dirName = 'js/'
    26. elif ext == 'css':
    27. dirName = 'css/'
    28. elif ext in ['jpg', 'png', 'gif']:
    29. dirName = 'images/'
    30. else:
    31. continue
    32. # 文件夹不存在 则创建文件夹
    33. if not os.path.exists(dirName):
    34. os.mkdir(dirName)
    35. # # 判断文件格式及是否已存在
    36. fileName_end = dirName + fileName
    37. if not os.path.isfile(fileName_end):
    38. # 处理相对路径资源
    39. if file[1:8] == 'uploads':
    40. file = main_url + file
    41. elif file[0:7] == 'scripts':
    42. continue
    43. try:
    44. pic = get_origin_img(file, main_url)
    45. fp = open(fileName_end, 'wb')
    46. fp.write(pic.content)
    47. fp.close()
    48. except BaseException:
    49. print('获取【%s】失败' % file)
    50. continue
    51. content = content.replace(file, '../' + fileName_end)
    52. return content

    获取资源的请求方法

    1. def get_origin_img(url, referer):
    2. """ 请求网址图片 增加请求头 返回图片二进制 """
    3. A = requests.Session()
    4. A.headers = {
    5. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:86.0) Gecko/20100101 Firefox/86.0',
    6. 'Accept': 'image/webp,*/*',
    7. 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
    8. 'Connection': 'keep-alive',
    9. 'Referer': referer,
    10. }
    11. return A.get(url, timeout=10)

    3.把网页内容写入本地文件

    1. def record_article(fileName, dirName, content):
    2. """ 文章内容写入处理 """
    3. if not os.path.exists(dirName):
    4. # 递归创建目录
    5. os.makedirs(dirName)
    6. f = os.open(dirName + '/' + fileName, os.O_RDWR | os.O_CREAT)
    7. os.write(f, str.encode(content))
    8. os.close(f)

    最后调用方法:

    1. html = get_html(url)
    2. content = get_all_img(html.text)
    3. record_article('首页.html', '首页', content)

    效果如下:

    访问本地首页html文件,与原网站一致

     

  • 相关阅读:
    【Unity脚本】使用脚本操作游戏对象的组件
    SAP BASIS SET_PARAMETER_ID_TOO_LONG
    javaVue社区蔬果商城计算机毕业设计MyBatis+系统+LW文档+源码+调试部署
    GCC编译器生成库文件并编译
    一比一还原axios源码(零)—— 是结束亦是开始
    ubuntu云服务器怎么做好初始安全设置
    【C++】STL详解(十一)—— unordered_set、unordered_map的介绍及使用
    华新集团再冲刺港交所上市:上半年收入2.6亿元,张德红为董事长
    【季报分析】百度2022年Q3:逆势而上
    【普通人解题】leetcode 62. 不同路径
  • 原文地址:https://blog.csdn.net/json_ligege/article/details/127068915