当前 discord.py (async.io) 代码,用于打印随机纽约时报文章的链接。
@client.command()
async def news(ctx):
url = 'https://www.nytimes.com/section/us'
r = requests.get(url)
soup = BeautifulSoup(r.content)
articles = soup.find_all('a')
newslist = []
for article in articles:
newslist.append(article['href'])
news = random.choice(newslist)
while "2020" not in news:
news = random.choice(newslist)
else:
await ctx.send('https://www.nytimes.com' + news)
由于页面中的每个链接都被附加到新闻列表中,因此在打印/等待ctx.send之前,正在检查“2020”,这意味着它是一篇文章。有没有办法做一个find_all('a')只找到包含“2020”的链接,或者只附加包含“2020”的链接?这些方法会更有效吗?
慕容3067478
相关分类