在之前开发的的“板报”模块存在这样一个问题:当转载别人的文章,文章中有插图时,转载后的文章引用了原文的图片,当原文作者从服务器上删除了图片,或者图片链接不可用之后,所转载的文章中的插图也就不可显示,给浏览文章的用户带来了不便。 class ImageDownloader(threading.Thread,BrowserBase): def __init__(self,wiki): self.html = wiki.content self.wiki = wiki threading.Thread.__init__(self) def get_new_url(self,img_url): """ 将图片下载,并返回一个本地路径 """ name = 'wiki_%s_%s' %(self.wiki.id,time.time()) file_name = '/www/pythoner/static/upload/%s.jpg' %name try: urllib.urlretrieve(img_url,file_name) except Exception,e: return False else: return '/static/upload/%s.jpg' %name def run(self): soup = BeautifulSoup(self.html) img_soup = soup.findAll('img') if not img_soup: return # 找到文章中所有插图的链接 imgs = [] for img in img_soup: try: remote_url = img['src'] except Exception,e: continue local_url = self.get_new_url(remote_url) if not local_url: continue else: li = (remote_url,local_url) imgs.append(li) # 替换原文中的图片链接地址 new_html = self.html for img in imgs: self.title = img[0] try: remote_url = img[0] local_url = img[1] except: continue else: new_html = new_html.replace(remote_url,local_url) # 保存 self.wiki.content = new_html self.wiki.save()
|
|
来自: 昵称QAb6ICvc > 《python》