我首先要说我对 Python 非常陌生。我一直在用 discord.py 和 Beautiful Soup 4 构建一个 Discord 机器人。这是我所在的位置:
@commands.command(hidden=True)
async def roster(self):
"""Gets a list of CD's members"""
url = "http://www.clandestine.pw/roster.html"
async with aiohttp.get(url) as response:
soupObject = BeautifulSoup(await response.text(), "html.parser")
try:
text = soupObject.find_all("font", attrs={'size': '4'})
await self.bot.say(text)
except:
await self.bot.say("Not found!")
这是输出:
现在,我尝试使用
get_text()
以多种不同的方式从这段代码中去除括号和 HTML 标签,但每次都会引发错误。我如何才能实现这一目标或将此数据输出到数组或列表中,然后只打印纯文本?
最佳答案
代替
text = soupObject.find_all("font", attrs={'size': '4'})
有了这个:
all_font_tags = soupObject.find_all("font", attrs={'size': '4'})
list_of_inner_text = [x.text for x in all_font_tags]
# If you want to print the text as a comma separated string
text = ', '.join(list_of_inner_text)
关于python - 在 BS4 中使用 find_all 获取文本作为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42652147/