日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python下载微信公众号文章和图片保存至本地

發布時間:2023/12/20 python 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python下载微信公众号文章和图片保存至本地 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

思路

獲取到微信公眾號的文章之后,使用 BeautifulSoup 和正則表達式 解析出文章標題和包含正文的html.

獲取到html之后,用正則表達式獲取圖片下載鏈接,下載成功后將微信的鏈接替換成本地圖片鏈接。

運行效果


代碼

import requests from re import findall from bs4 import BeautifulSoup import time import osweixin_title="" weixin_time=""#獲取微信公眾號內容,保存標題和時間 def get_weixin_html(url):global weixin_time,weixin_titleres=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)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修改為srcfor url in result:html=html.replace('data-src="'+url+'"','src="'+url+'"')return html#上傳圖片至服務器 def download_pic(content):pic_path='pic/'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=1flag=Truepic_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 = Falseprint('已下載第' + str(index) +'張圖片.')count += 1time.sleep(1)except:count+=1time.sleep(1)if count>10:print("下載出錯:",pic_url)return contentif __name__ == "__main__":#獲取htmlinput_flag=Truewhile input_flag:weixin_url=input('請輸入微信文章鏈接后按Enter:')re=findall(r'http[s]?:\/\/mp.weixin.qq.com\/s\/[0-9a-zA-Z_]+',weixin_url) if len(re)<=0:print("鏈接有誤,請重新輸入!")else:input_flag=Falsecontent=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下载微信公众号文章和图片保存至本地的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。