Python下载微信公众号文章和图片保存至本地
生活随笔
收集整理的這篇文章主要介紹了
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下载微信公众号文章和图片保存至本地的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 产品各类型之间的关系
- 下一篇: 解决Python安装pyqt5-tool