通过python加载网站的内容

时间:2011-03-25 15:24:50

标签: python load

如何通过python从网站加载特定内容?例如,我想加载博客的一些帖子并将它们显示在我自己的网站上。我该怎么做?

2 个答案:

答案 0 :(得分:4)

答案:

import urllib2
from BeautifulSoup import BeautifulSoup

def fetchtags(req, name, attrs, num):
        try:
            website = urllib2.urlopen(req)
        except urllib2.HTTPError, e:
            print 'A problem occured. Please try again.'
            return
        soup = BeautifulSoup(website,
                             convertEntities=BeautifulSoup.HTML_ENTITIES)
        tags = soup.findAll(name=name,
                            attrs=attrs,
                            limit=num)
        return tags

然后你就可以使用它:

fetchtags('http://www.website.com', 'div', {'class':'c'}, 10)

从指定的网址中获取10个c类div ...

有关返回对象的更多详细信息,请参阅Beautiful Soup。

答案 1 :(得分:2)

urlliburllib2可让您加载原始HTML。诸如BeautifulSoup和lxml之类的HTML解析器将允许您解析原始HTML,以便您可以获得您关注的部分。诸如Mako,Cheetah等模板引擎将允许您生成HTML,以便您可以显示网页。