Python3 - 代码停止工作并显示名称错误

Python3 - Code stopped to work and shows name error

我有以下代码,我总是 运行 在我的服务器上 (Python3)。

import requests
import re
import json

links = json.loads(open('links.json').read())

for link in links:

        url = link.lower()

        headers = {
           'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36',
           'Content-Type': 'text/html',
        }

        r = requests.get(url)
        response = requests.get(r.url, headers=headers)
        response = response.text
        response = response.rstrip()
        try:
                linkdown = re.findall('(https?:\/\/k2s.cc/file[^\s]+(\.mp4|avi|AVI|wmv|WMV|flv|FLV|mpg|MPG|MP4))', response)[0]
        except IndexError:
                print('Linha não encontrada')
        string = ''.join(str(linkdown[0]))
        print(string)

        with open("k2s.txt", "a") as myfile:
           myfile.write(string  + "\n")

几周前,代码停止工作并开始显示此错误:

string = ''.join(str(linkdown[0]))

NameError: name 'linkdown' is not defined

我真的不明白发生了什么,因为代码没有被修改并且总是正确运行。

在此先感谢您的帮助!

你的错误的问题是这一行:

try:
   linkdown = re.findall('(https?:\/\/k2s.cc/file[^\s]+(\.mp4|avi|AVI|wmv|WMV|flv|FLV|mpg|MPG|MP4))', response)[0]
except IndexError:
   print('Linha não encontrada')

没有做任何事情以防 linkdown 实际失败,并且未创建变量 linkdown,因此出现错误:

NameError: name 'linkdown' is not defined

尝试添加:

try:
   linkdown = re.findall('(https?:\/\/k2s.cc/file[^\s]+(\.mp4|avi|AVI|wmv|WMV|flv|FLV|mpg|MPG|MP4))', response)[0]
except IndexError:
   print('Linha não encontrada')
   continue # or linkdown = None #or do smtg here

此外,测试是否存在可能会更好:

linkdown = re.findall('(https?:\/\/k2s.cc/file[^\s]+(\.mp4|avi|AVI|wmv|WMV|flv|FLV|mpg|MPG|MP4))', response)

if linkdown:
   #do something here