Skip to main content
 首页 » 编程设计

python之通过python加载网站内容

2025年05月04日18cyq1162

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

请您参考如下方法:

一个答案:

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) 

从指定的 url 获取 10 个 c 类的 div...

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