1

我正在构建一个实用程序来从一堆不同格式的网站中提取相似的数据(标题和日期),BeautifulSoup 非常有帮助。我还没有找到存储我正在使用的 BeautifulSoup 函数的好方法,这样我就不必为每个站点构建一个新函数。这是一个例子:

soup = BeautifulSoup(html)
title = soup.find("h4", "title").text    # extract title
date = soup.find('li', 'when').em.text       # extract date

每个站点将有一组不同的节点来解析。拥有数百个站点,为每个站点构建一个独特的功能是很愚蠢的。有没有办法将 soup.find('x').etc.etc 调用存储在 URL 旁边的表格中,并在一个函数中应用正确的 BeautifulSoup 调用?希望这是有道理的。

谢谢!

4

1 回答 1

0

嗯,假设我理解你的帖子,这行得通吗?

linkInstructions = {
  "url1": {
    "title": lambda n: n.find('h4', 'title').text,
    "date": lambda n: n.find('li', 'when').em.text
  },
  "url2": {
    "title": lambda n: n.find('h3', 'title').text,
    "date": lambda n: n.find('li', 'when').strong.text
  }
  # and so forth
} 

def parseNode(node, url):
  # let 'node' be the result of BeautifulSoup(html)
  # and 'url' be the url of the site    

  result = {}

  for key,func in linkInstructions[url].iteritems():
    result[key] = func(node)

  # would return a dict with the structure {'title': <title>, 'date': <date>}
  return result

编辑:糟糕,枚举不是正确使用的功能。

于 2013-03-05T07:32:52.067 回答