Else是无效的语法



我写了一些代码,将下载一个网页,然后搜索一个特定的字符串,我知道这是一个低效的方式去做,但这是我选择的方式,无论如何,代码总是出现一个无效的语法为其他。欢迎任何帮助!代码:

import requests
from discord import Webhook, RequestsWebhookAdapter
#download website and turns into a .txt file
while true:
print('Beginning file download with requests')
url = str(input("Enter Profile ID:"))
r = requests.get(url)
with open('/Users/Computer/Desktop/Notification/[profile.txt', 'wb') as f:
f.write(r.content)
# Retrieve HTTP meta-data
print(r.status_code)
print(r.headers['content-type'])
print(r.encoding)
#opens text file and searches for a certain keyword
with open('/Users/Computer/Desktop/Notification/[profile.txt') as f:
if 'avatar-status online profile-avatar-status icon-online' in f.read():#if it finds the keyword it sleeps and then retries
time.sleep(20)
continue
#if it doesnt find the keyword (meaning they are offline) it sends you a message through discord webhook
else:
webhook = Webhook.from_url("YOUR WEBHOOK HERE!", adapter=RequestsWebhookAdapter())
webhook.send("Found string")

问题继续。你不能在'if'之外放置任何其他代码,然后使用else。

  • True
  • T必须大写
  • 您的continuewhile之外,因为它没有缩进。
  • 你的continueif之外,因为它没有缩进,然后从if断开else
  • 你的else正文没有缩进
while True: # Capitalize
print('Beginning file download with requests')
url = str(input("Enter Profile ID:"))
r = requests.get(url)
with open('/Users/Computer/Desktop/Notification/[profile.txt', 'wb') as f:
f.write(r.content)
# Indent everything below this
print(r.status_code)
print(r.headers['content-type'])
print(r.encoding)
#opens text file and searches for a certain keyword
with open('/Users/Computer/Desktop/Notification/[profile.txt') as f:
if 'avatar-status online profile-avatar-status icon-online' in f.read():
time.sleep(20)
continue # indent this to align with the sleep
else:
webhook = Webhook.from_url("YOUR WEBHOOK HERE!", adapter=RequestsWebhookAdapter()) # indent this to be in the else
webhook.send("Found string") # indent this too

进一步细化:

  • 你根本不需要额外的文件,搜索r.content的字节字符串
  • input()返回str(),所以你不需要转换它
  • if/else之后没有任何内容,所以你不需要continue
while True:
print('Beginning file download with requests')
url = input("Enter Profile ID:")
r = requests.get(url)
print(r.status_code)
print(r.headers['content-type'])
print(r.encoding)
if b'avatar-status online profile-avatar-status icon-online' in r.content:
time.sleep(20)
else:
webhook = Webhook.from_url("YOUR WEBHOOK HERE!", adapter=RequestsWebhookAdapter())
webhook.send("Found string")

Python使用缩进作为语法,因此它不能将'else'与if语句相关联。

尝试缩进'continue'和'else'之后的行:

with open('/Users/Computer/Desktop/Notification/[profile.txt') as f:
if 'avatar-status online profile-avatar-status icon-online' in f.read():#if it finds the keyword it sleeps and then retries
time.sleep(20)
continue
#if it doesnt find the keyword (meaning they are offline) it sends you a message through discord webhook
else:
webhook = Webhook.from_url("YOUR WEBHOOK HERE!", adapter=RequestsWebhookAdapter())
webhook.send("Found string")

最新更新