在BS4中使用find_all很困难

时间:2017-02-12 14:23:40

标签: python python-2.7 web-scraping beautifulsoup

我使用Beautiful Soup 4将一些文字从网页刮到Discord机器人。

@commands.command(hidden=True)
async def roster(self):
"""A script using BS4."""

url = "http://www.clandestine.pw/roster.html"
async with aiohttp.get(url) as response:
    soupObject = BeautifulSoup(await response.text(), "html.parser")
try:
    txt = soupObject.find("font", attrs={'size': '4'}).get_text()
    await self.bot.say(txt)
except:
    await self.bot.say("Not found!")

运行命令,返回" ThaIIen" (正如它应该)。如果我只是将find更改为find_all,则会返回"未找到!"为什么?难道不能返回文档中的每个字体大小为4的文本吗?

1 个答案:

答案 0 :(得分:1)

find_all("font", attrs={'size': '4'})将返回:

[font_tag1, font_tag2, font_tag3 ....]

find("font", attrs={'size': '4'})将返回:

font_tag1

.get_text()是标记对象的方法,而不是对象列表,因此,当您运行find_all().get_text()时会引发Exception