我收到此错误消息。请帮我解决这个问题。
import discord
import requests
from bs4 import BeautifulSoup
client = discord.Client(intents=discord.Intents.default())
def get_latest_article():
url = 'https://www.rockstargames.com/newswire'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
article = soup.find('div', {'class': 'featured-post'}).find('a')
title = article.text.strip()
url = article['href']
return title, url
@client.event
async def on_ready():
channel = client.get_channel(channel_id)
title, url = get_latest_article()
await channel.send(f'**{title}**\n{url}')
client.run('bot_token_here')
我正在尝试创建一个 discord 机器人,它将从 https://www.rockstargames.com/newswire 发送消息到我特定的 discord 频道。
错误正是它所说的 -
NoneType
没有 find
属性。它指向发生错误的行;
article = soup.find('div', {'class': 'featured-post'}).find('a')
因此,要么
soup
是 None
,要么第一个 find 返回 None
。一个有用的调试技巧是将该行一分为二,这样您就可以自己确定问题所在:
featured_post_div = soup.find('div', {'class': 'featured-post'})
article = featured_post_div.find('a')
然后你就知道
soup
是None还是featured_post_div
是None.
但显然,是后者。
soup.find('div', {'class': 'featured-post'})
返回 None 并且没有找到任何东西,所以显然第二次查找将失败。这意味着该网站上没有具有该类名的 div 元素。您将不得不返回网站并使用检查/其他工具找到您想要的元素及其定义属性,然后重试。