【问题标题】:Difficulty with find_all in BS4BS4 中 find_all 的困难
【发布时间】:2025-12-17 15:55:01
【问题描述】:

我正在使用 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 的文本吗?

【问题讨论】:

    标签: python python-2.7 web-scraping beautifulsoup


    【解决方案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

    【讨论】: