# 使用flask实现的微信公众号文章封面图爬取 **Repository Path**: knighthood2001/flask_demo2 ## Basic Information - **Project Name**: 使用flask实现的微信公众号文章封面图爬取 - **Description**: flask实现获取公众号文章封面 - **Primary Language**: Python - **License**: AGPL-3.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2024-04-08 - **Last Updated**: 2024-04-10 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README > 📚**博客主页:[knighthood2001](https://blog.csdn.net/knighthood2001)** > > ✨**公众号:[认知up吧](https://mp.weixin.qq.com/s/Q29t9kZrSot3w9lKJs2sWw) (目前正在带领大家一起提升认知,感兴趣可以来围观一下)** > > 🎃**知识星球:[【认知up吧|成长|副业】介绍](https://mp.weixin.qq.com/s/Vl2rd6j7Q51mVitshrTWaQ)** > > **❤️感谢大家点赞👍🏻收藏⭐评论✍🏻,您的三连就是我持续更新的动力❤️** > > **🙏笔者水平有限,欢迎各位大佬指点,相互学习进步!** # 前言 该项目对于初学者来说比较不错,并且以后可以将其作为一个简单的模板,照着该就行。比如你输入要爬取的东西,然后点击,将爬取的东西显示出来。都可以用这个模板。 如果有些内容不懂的,可以点击我的博客主页查找相应文章,我几乎所有东西都讲到过。 # 如何使用 首先需要自己安装虚拟环境 然后安装flask项目 运行`公众号文章封面的爬取.py`即可 # 项目讲解 `templates`模板目录下的`index.html`文件如下 ```html 打印内容

获取公众号文章封面



``` 长得是下面这样的, ![img.png](readme_img/img.png) `wechat_image_get.py`文件是爬虫,用于实现通过公众号文章链接爬取封面并以时间戳为文件名保存到`image`文件夹下(该文件夹如果不存在,会自动产生) 具体代码如下: ```python import requests import re import os #TODO 使用时间戳当作文件名称 def get_time(): import time timestamp = int(time.time()) return timestamp #TODO 实现从网页图片保存到本地,输入为图片网址和保存路径 def image_save(image_url, path): if not os.path.exists(path): # 如果文件夹不存在,则创建 os.makedirs(path) # 发送 GET 请求获取图片数据 response = requests.get(image_url) # 确保请求成功 if response.status_code == 200: image_name = get_time() image_name = "{}.jpg".format(image_name) # 指定图片保存路径 save_path = os.path.join(path, image_name) # 这里将图片保存在名为 images 的文件夹中 # 将图片数据写入文件 with open(save_path, 'wb') as f: f.write(response.content) print(f'图片已保存为: {save_path}') return save_path else: print(f'下载图片失败,状态码: {response.status_code}') # TODO 微信公众号获取封面并保存,输入网址 def get_image(wechat_url): response = requests.get(wechat_url) # 检查响应状态码,200表示请求成功 if response.status_code == 200: # 定义包含目标网址的字符串 source_code = response.text # 使用正则表达式提取网址 url_pattern = re.compile(r'cdn_url_1_1 = "(.*?)"') matches = url_pattern.findall(source_code) # 输出提取到的网址 if matches: print(matches[0]) # 图片网址 file = image_save(matches[0], "images") return matches[0], file if __name__ == '__main__': # 定义目标网页的URL url = 'https://mp.weixin.qq.com/s/d7DUHB-hT8DExjpxsEncQw' print(get_image(url)) ``` 和之前相比,我多了以下一行代码,用来实现从本地读取图片路径,然后在html中显示 ```python return save_path ``` `公众号文章封面的爬取.py`的代码如下 ```python from flask import Flask, request, render_template from flask import send_file from flask import redirect from wechat_image_get import get_image app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/process_input', methods=['POST']) def process_input(): input_url = request.form['input_text'] img = get_image(input_url) # return send_file(readme_img, mimetype='image/jpeg') #图片格式不太可用 # return redirect(readme_img)#出现此图片来自微信公众平台,未经允许不可引用 # return readme_img # 该方法导致只是链接,但是点击不能跳转。 return send_file(img[1]) if __name__ == '__main__': app.run(debug=True) ``` 注意以下的index.html中的表单,其中的action="/process_input",由于前端的跳转我不是特别清楚。这里大致意思就是点击获取后,会跳转到/process_input路由,因此你可以在该路由中显示出来。 ```html


``` 这里需要注意的是,我图片是先保存到本地,然后把本地图片渲染到html中,而不是将该图片对应的网址渲染出来, 因为我试过flask的`redirect`重定向,他会提示`此图片来自微信公众平台,未经允许不可引用`,所有这种方法就不可行了,说明微信中有反爬措施。 `send_file`是flask用来发送文件到客户端的函数,可以是图片。所所以我这里使用该函数,实现在浏览器中展示图片。