分享

用python处理转载文章中的插图(实践与应用)

 昵称QAb6ICvc 2013-02-19

  在之前开发的的“板报”模块存在这样一个问题:当转载别人的文章,文章中有插图时,转载后的文章引用了原文的图片,当原文作者从服务器上删除了图片,或者图片链接不可用之后,所转载的文章中的插图也就不可显示,给浏览文章的用户带来了不便。

    为解决这个问题,我想到了如下思路。在保存(新增&修改)时做3件事情:1,用beautifulsoup从文章的html中提取出图片的链接.2,用urllib2将图片下载到本地服务器上。3,将文章html中的img标签的src属性替换成本地服务器上图片的链接地址。但这些操作会消耗较长的时间,如果将它放在处理保存的业务逻辑中,用户会等待很长时间,服务器才会返回保存成功的信息,体验不够好,因此,可以起一个线程来完成上述3个操作

部分代码如下。注意:ImagDownloader的父类“BrowserBase”的源代码见:http:///code/40/

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()



在处理保存文章的业务逻辑中,只需要ImageDownloader(new_wiki).start()即可启动该线程
注意:是start()方法,不是run()方法。如果用run()方法的话,程序会被阻塞

通过以上修改,在转载文章时,保存文章时,所有包含的图片都会被下载到本地并且替换图片的链接,这些操作都是在一个新的线程中完成的,

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多