我在使用 Python 和 BeautifulSoup4 时遇到了一个有趣的问题。 我的方法通过给定的餐厅(字典键)获取本地学生餐厅当天的菜单,然后显示这些菜单。
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 的一部分,但目前它仅适用于我的测试机器(带有 Python 2.7.3 的 Ubuntu 12.04),但在运行该机器人的另一台机器(带有 Python 2.6.5 的 Xubuntu)上它失败了。
行后
soup = BeautifulSoup(urllib.urlopen("http://murkinat.appspot.com"))
>>> type(soup)
<class 'bs4.BeautifulSoup'>
我可以打印它,它显示拥有所有应该的内容,但它找不到任何东西。如果我这样做:
>>> 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
我对此完全一无所知。我有许多类似的 BeautifulSoup 解析方法,它们在机器人上运行得很好(它解析 url 的标题和维基百科的内容),但这个一直困扰着我。
有人知道吗?我只能想出它与我的 Python 版本有关,这听起来很奇怪,因为在其他地方 BeautifulSoup4 都工作得很好。
最佳答案
我相信你有different parsers installed on the two machines 。 html5lib 解析器在给定标记上失败,从而产生不良行为。 lxml 和 html.parser 解析器正确解析标记并且不会给出不良行为。
当编写将在多台机器上运行的代码时,最好明确说明您要使用哪个解析器:
BeautifulSoup(data, "lxml")
这样,如果未安装适当的解析器,您将收到错误。
关于python - BeautifulSoup 在两种环境下的工作方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11459990/