如何通过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。
关于python - 通过python加载网站内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5434520/