【发布时间】:2021-07-24 02:47:13
【问题描述】:
问题出在我使用!firsttime 命令时出现错误提示
Ignoring exception in command firsttime:
Traceback (most recent call last):
File "goodreads.py", line 27, in firsttime_command
for link in links.reverse():
TypeError: 'NoneType' object is not iterable
上面的异常是下面异常的直接原因
这里是代码
import re
import json
import aiohttp
from datetime import datetime
import discord
from discord.ext import commands, tasks
JSON_PATH = "json file path"
REGEX = "<a class=readable bookTitle href=(.*)[?].*>"
URL = "https://www.goodreads.com/genres/new_releases/fantasy"
CHANNEL_ID = 834867425677803580
class Goodreads(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
self.check_website.start()
@commands.command(name="firsttime")
async def firsttime_command(self, ctx):
links = await self.make_request()
data = {}
now = str(datetime.utcnow())
for link in links.reverse():
data[link] = now
with open(JSON_PATH, "w") as f:
json.dump(data, f, indent=2)
@tasks.loop(minutes=1)
async def check_website(self):
links = await self.make_request()
with open(JSON_PATH, "r") as f:
data = json.load(f)
for link in links:
if link not in data.keys():
await self.bot.get_channel(CHANNEL_ID).send(f"A new fantasy book released.\n{link}")
data[link] = str(datetime.utcnow())
with open(JSON_PATH, "w") as f:
json.dump(data, f, indent=2)
async def make_request(self):
async with aiohttp.ClientSession() as ses:
async with ses.get(URL) as res:
text = await res.text()
text = text.replace("\\\"", "")
return re.findall(REGEX, text)
bot = commands.Bot(command_prefix="!")
bot.add_cog(Goodreads(bot))
@bot.event
async def on_connect():
print("Connected")
@bot.event
async def on_ready():
print("Ready")
bot.run("tokens")
【问题讨论】:
-
它说:
The above exception was the direct cause of the following exception,下面的异常是什么? -
我想我在其他问题中看到了这段代码。你重复了吗?看来您仍然没有学习如何调试代码 - 即使使用
print()。如果代码显示您在哪一行出现错误,那么首先您可以使用print()检查变量中的值 - 似乎您在links中得到None并且您运行links.reverse()这意味着None.reverse()。当你得到None时,你应该跳过所有代码。 -
如果你从`self.make_request()`中得到
links,那么你应该检查你在变量中得到的make_request()——也许你使用了错误的值或者在某些页面上findall(REGEX, ...)可以' t 找到元素,它给出None。再次,您可以使用pritn()对其进行调试 - 检查您从服务器获得的 HTML 内容。也许它发送的 HTML 与您期望的不同 - 即。它可能会发送错误消息、机器人或 ReCaptch 警告等。所以很快你就必须调试代码 - 并检查变量中的所有内容 - 不要信任代码。 -
你之前测试过你的正则表达式吗?这是错误的。我检查了页面上的 HTML,没有
class=readable bookTitle,但class=\"readable bookTitle\"和href=\"...\"而不是href=...。顺便说一句:你必须记住aiohttp可以获取 HTML,但它不能运行JavaScript- 所以如果你在浏览器中手动检查 HTML,那么首先关闭JavaScript。
标签: python python-3.x discord discord.py bots