BeautiulSoup在两种环境下的工作方式不同

2024-10-04 09:20:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python和BeautifulSoup4中遇到了一个有趣的问题。 我的方法通过给定的餐厅(dict键)获取本地学生餐厅当天的菜单,然后显示这些菜单。在

def fetchFood(restaurant):
  # Restaurant id's
  restaurants = {'assari': 'restaurant_aghtdXJraW5hdHIaCxISX1Jlc3RhdXJhbnRNb2RlbFYzGMG4Agw', 'delica': 'restaurant_aghtdXJraW5hdHIaCxISX1Jlc3RhdXJhbnRNb2RlbFYzGPnPAgw', 'ict': 'restaurant_aghtdXJraW5hdHIaCxISX1Jlc3RhdXJhbnRNb2RlbFYzGPnMAww', 'mikro': 'restaurant_aghtdXJraW5hdHIaCxISX1Jlc3RhdXJhbnRNb2RlbFYzGOqBAgw', 'tottisalmi': 'restaurant_aghtdXJraW5hdHIaCxISX1Jlc3RhdXJhbnRNb2RlbFYzGMK7AQw'}

if restaurants.has_key(restaurant.lower()):
  soup = BeautifulSoup(urllib.urlopen("http://murkinat.appspot.com"))
  meal_div = soupie.find(id="%s" % restaurants[restaurant.lower()]).find_all("td", "mealName hyphenate")
  mealstring = "%s: " % restaurant
  for meal in meal_div:
    mealstring += "%s / " % meal.string.strip()
  mealstring = "%s @ %s" % (mealstring[:-3], "http://murkinat.appspot.com")
return mealstring

else:
  return "Restaurant not found"

它将是我的IRCBot的一部分,但目前它只在我的测试机器上工作(ubuntu12.04和python2.7.3),但在另一台运行bot的机器(Xubuntu和python2.6.5)上它失败了。在

行之后

^{pr2}$

我可以把它打印出来,它显示了所有应该包含的内容,但是它找不到任何东西。如果我这样做:

>>> print soup.find(True)
None

>>> soup.get_text()
u'?xml version="1.0" encoding="utf-8" ?'

它停止读取第一行,尽管在另一台机器上,它可以完美地读取所有内容。在

输出应如下所示(来自此时具有餐厅参数“Tottisalmi”的工作机器):

    Tottisalmi: Sveitsinleike, kermaperunat / Jauheliha-perunamusaka / Uuniperuna, kylmäsavulohitäytettä / Kermainen herkkusienikastike @ http://murkinat.appspot.com

我完全不懂这个。我有很多类似的beauthulsoup解析方法,在bot上工作得很好(它解析url和Wikipedia的标题),但是这个方法一直困扰着我。在

有人知道吗?我只能和我的Python版本有关,这听起来很奇怪,因为BeautifulSoup4在其他任何地方都能正常工作。在


Tags: 方法com机器http菜单find餐厅restaurant
1条回答
网友
1楼 · 发布于 2024-10-04 09:20:37

我相信你有。html5lib解析器对给定的标记失败,从而导致错误的行为。lxml和html.parser解析器正确地解析标记,不会给出错误的行为。在

在编写将在多台计算机上运行的代码时,最好明确说明要使用哪个解析器:

BeautifulSoup(data, "lxml")

这样,如果没有安装相应的解析器,您将得到一个错误。在

相关问题 更多 >