Python实现快速保存微信公众号文章中的图片
作者:用余生去守护 发布时间:2021-02-18 23:03:25
标签:Python,保存,公众号,文章,图片
一、实现效果(以槿泉壁纸为例)
二、实现过程
1.新建一个link文本,将需要下载的文章链接依次保存;
2.新建一个.py文件,将下面的源码复制进去;
3.新建一个pic文件夹,用来保存图片;
4.运行即可;
三、源码
sound code
代码如下(示例):
import requests
from re import findall
from bs4 import BeautifulSoup
import time
import os
import sys
weixin_title=""
weixin_time=""
#获取微信公众号内容,保存标题和时间
def get_weixin_html(url):
global weixin_time,weixin_title
res=requests.get(url)
soup=BeautifulSoup(res.text,"html.parser")
#获取标题
temp=soup.find('h1')
weixin_title=temp.string.strip()
#使用正则表达式获取时间
# result=findall(r'[0-9]{4}-[0-9]{2}-[0-9]{2}.+:[0-9]{2}',res.text)
result=findall(r"(\d{4}-\d{1,2}-\d{1,2})",res.text)
weixin_time=result[0]
#获取正文html并修改
content=soup.find(id='js_content')
soup2=BeautifulSoup((str(content)),"html.parser")
soup2.div['style']='visibility: visible;'
html=str(soup2)
pattern=r'http[s]?:\/\/[a-z.A-Z_0-9\/\?=-_-]+'
result = findall(pattern, html)
#将data-src修改为src
for url in result:
html=html.replace('data-src="'+url+'"','src="'+url+'"')
return html
#上传图片至服务器
def download_pic(content):
pic_path= 'pic/' + str(path)+ '/'
if not os.path.exists(pic_path):
os.makedirs(pic_path)
#使用正则表达式查找所有需要下载的图片链接
pattern=r'http[s]?:\/\/[a-z.A-Z_0-9\/\?=-_-]+'
pic_list = findall(pattern, content)
for index, item in enumerate(pic_list,1):
count=1
flag=True
pic_url=str(item)
while flag and count<=10:
try:
data=requests.get(pic_url);
if pic_url.find('png')>0:
file_name = str(index)+'.png'
elif pic_url.find('gif')>0:
file_name=str(index)+'.gif'
else:
file_name=str(index)+'.jpg'
with open( pic_path + file_name,"wb") as f:
f.write(data.content)
#将图片链接替换为本地链接
content = content.replace(pic_url, pic_path + file_name)
flag = False
print('已下载第' + str(index) +'张图片.')
count += 1
time.sleep(1)
except:
count+=1
time.sleep(1)
if count>10:
print("下载出错:",pic_url)
return content
def get_link(dir):
link = []
with open(dir,'r') as file_to_read:
while True:
line = file_to_read.readline()
if not line:
break
line = line.strip('\n')
link.append(line)
return link
path = 'link.txt'
linklist = get_link(path)
print(linklist)
s = len(linklist)
if __name__ == "__main__":
#获取html
input_flag=True
while input_flag:
# for j in range(0,s):
# pic = str(j)
j = 1
for i in linklist:
weixin_url = i
path = j
j += 1
#weixin_url=input()
re=findall(r'http[s]?:\/\/mp.weixin.qq.com\/s\/[0-9a-zA-Z_]+',weixin_url)
if len(re)<=0:
print("链接有误,请重新输入!")
else:
input_flag=False
content=get_weixin_html(weixin_url)
content=download_pic(content)
#保存至本地
with open(weixin_title+'.txt','w+',encoding="utf-8") as f:
f.write(content)
with open(weixin_title+'.html','w+',encoding="utf-8") as f:
f.write(content)
print()
print("标题:《"+weixin_title+"》")
print("发布时间:"+weixin_time)
四、Python正则表达式匹配日期与时间
import re
from datetime import datetime
test_date = '小明的生日是2016-12-12 14:34,小张的生日是2016-12-21 11:34 .'
test_datetime = '小明的生日是2016-12-12 14:34,.小晴的生日是2016-12-21 11:34,好可爱的.'
# date
mat = re.search(r"(\d{4}-\d{1,2}-\d{1,2})",test_date)
print mat.groups()
# ('2016-12-12',)
print mat.group(0)
# 2016-12-12
date_all = re.findall(r"(\d{4}-\d{1,2}-\d{1,2})",test_date)
for item in date_all:
print item
# 2016-12-12
# 2016-12-21
# datetime
mat = re.search(r"(\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2})",test_datetime)
print mat.groups()
# ('2016-12-12 14:34',)
print mat.group(0)
# 2016-12-12 14:34
date_all = re.findall(r"(\d{4}-\d{1,2}-\d{1,2}\s\d{1,2}:\d{1,2})",test_datetime)
for item in date_all:
print item
# 2016-12-12 14:34
# 2016-12-21 11:34
## 有效时间
# 如这样的日期2016-12-35也可以匹配到.测试如下.
test_err_date = '如这样的日期2016-12-35也可以匹配到.测试如下.'
print re.search(r"(\d{4}-\d{1,2}-\d{1,2})",test_err_date).group(0)
# 2016-12-35
# 可以加个判断
def validate(date_text):
try:
if date_text != datetime.strptime(date_text, "%Y-%m-%d").strftime('%Y-%m-%d'):
raise ValueError
return True
except ValueError:
# raise ValueError("错误是日期格式或日期,格式是年-月-日")
return False
print validate(re.search(r"(\d{4}-\d{1,2}-\d{1,2})",test_err_date).group(0))
# false
# 其他格式匹配. 如2016-12-24与2016/12/24的日期格式.
date_reg_exp = re.compile('\d{4}[-/]\d{2}[-/]\d{2}')
test_str= """
平安夜圣诞节2016-12-24的日子与去年2015/12/24的是有不同哦.
"""
# 根据正则查找所有日期并返回
matches_list=date_reg_exp.findall(test_str)
# 列出并打印匹配的日期
for match in matches_list:
print match
# 2016-12-24
# 2015/12/24
来源:https://blog.csdn.net/qq_45365214/article/details/125405386


猜你喜欢
- 本文实例讲述了js获取url传值的方法。分享给大家供大家参考,具体如下:js获取url参数值:index.htm?参数1=数值1&参
- 详解Python import方法引入模块的实例在Python用import或者from…import或者from…import…as…来导
- MySql 这个数据库绝对是适合dba级的高手去玩的,一般做一点1万篇新闻的小型系统怎么写都可以,用xx框架可以实现快速开发。可是数据量到了
- 本文介绍如果使用python汇总常用的图表,与Excel的点选操作相比,用python绘制图表显得比较比较繁琐,尤其提现在对原始数据的处理上
- vue使用formData传递文件类型的数据1.需求 传递文件类型的数据和其
- 在javascript里怎么样才能把int型转换成string型(1)var x=100 a = &nb
- 导读演示了使用PyTorch最近发布的新工具torchserve来进行PyTorch模型的部署。最近,PyTorch推出了名为torchse
- 本文主要介绍了python 边缘扩充方式的实现示例,具体如下:import cv2# big_pad=True:当目标图像高和宽均大于原图时
- 第一次在自己虚机上安装mysql 中间碰到很多问题 在这里记下来,分享一下。linux centOS 6mysql版本 mysql-5.7.
- 在python自动化中,经常会遇到对数据文件的操作,比如添加多名员工,但是直接将员工数据写在python文件中,不但工作量大,要是以后再次遇
- 一、状态介绍在了解其他概念之前,我们首先要了解进程的几个状态。在程序运行的过程中,由于 * 作系统的调度算法控制,程序会进入几个状态:就绪,运
- 首先对空格宽度的定义:空格,由于每个浏览器处理会有微小的不同,在这里我将可以选中的宽度作为空格的宽度。视觉宽度和可选中的宽度有 0~3px
- 函数原型:getopt.getopt(args, shortopts, longopts=[])参数解释:  
- 使用 Microsoft® SQL Server™ 2000,可以选择在一台计算机上安装 SQL Ser
- 简介使用的核心模块是python标准库中的zipfile模块。这个模块可以实现zip文件的各种功能,具体可以查看官方参考文档。这里的暴力破解
- 这篇博客给大家讲解在django中类似触发器的效果这篇教程分别会讲解插入记录后,删除记录前,删除记录后这三个部分相关环境 python 3.
- 一:获取指定文件夹的文件 procedure searchfile(path:string);//注意,path后面要有'\'
- 目录背景法1,不适用法2,已不能用法3:Appnium法4:模拟操作整体代码后续工作及扩展总结背景由于课题需要爬取朋友圈的内容作为研究数据,
- 我们可以用DataFrame的apply函数实现对多列,多行的操作。需要记住的是,参数axis设为1是对列进行操作,参数axis设为0是对行
- 可以使用 Application 对象在给定的应用程序的所有用户之间共享信息。基于 ASP 的应用程序同所有的 .asp 文件一样在一个虚拟