【发布时间】:2021-02-09 23:35:22
【问题描述】:
我正在创建一个 Discord 机器人,我从底部开始。我试图解决的第一部分是使用 BeautifulSoup。我当前的代码:
soup = BeautifulSoup(page, 'html.parser')
pbe_titles = soup.find_all('h1', attrs={'class': 'news-title'})
for tag in pbe_titles :
print(tag.text.strip())
到目前为止,这正是我需要它做的。
它检索由类“news-title”标识的标签之间的所有文本,即
<h1 class="news-title">text here</h1> 并打印出与该类关联的所有标签的所有文本。现在,我想获取 BeautifulSoup 找到的所有这些标题,并将它们存储到一个数组中,我可以将其打印到我的 discord 客户端中。
soup = BeautifulSoup(page, 'html.parser')
pbe_titles = soup.find_all('h1', attrs={'class': 'news-title'})
for tag in pbe_titles :
totalTags = [tag.text.strip()]
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$show'):
await message.channel.send(totalTags)
client.run(os.getenv('TOKEN'))
我在这里遇到的问题是totalTags = [tag.text.strip()] 只返回一个标题,而不是全部。但如果我只是坚持print(tag.text.strip()),它将打印 15 个以上的标题。我的阵列做错了什么?
【问题讨论】:
-
totalTags = [tag.text.strip() for tag in pbe_titles]? -
你当前的代码会覆盖而不是追加
-
在解决该部分后,我有一个后续问题。如果我想使用 BeautifulSoup 在我已经存在的标签中查找其他标签,我该怎么做?例如——在每个标题中,都有一个嵌入的 href 链接作为其指向另一个网站的链接——有没有办法创建一个二维数组来存储与每个标题关联的链接?
-
在列表理解中生成元组,然后转换为数据框。迭代器将是两个目标元素的父元素,或者如果与子/兄弟匹配作为另一个匹配,则为目标。
标签: python web-scraping beautifulsoup discord.py read-eval-print-loop