【问题标题】:Python3 - Code stopped to work and shows name errorPython3 - 代码停止工作并显示名称错误
【发布时间】:2019-08-01 02:30:16
【问题描述】:

我有以下代码,我总是在我的服务器 (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' 未定义

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

提前感谢您的帮助!

【问题讨论】:

  • re.findall('blablabla', response)[0] 可能会失败,因为找不到匹配项。然后,您不是允许程序因错误而失败,而是显式地捕获异常、打印并允许程序即使在没有找到匹配项时也能恢复。如果找不到匹配项,您希望发生什么?
  • 代码是你写的吗?该错误意味着该行 - linkdown = re.findall('(https?:\/\/k2.... 未执行。

标签: python python-3.x nameerror


【解决方案1】:

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

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' 未定义

尝试添加:

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

【讨论】:

  • 也许在except 套件中加入continue 语句。
  • 刚刚也想过@wwii。谢谢你
  • 谢谢@wwii,continue 语句解决了问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-28
  • 2014-11-06
  • 2014-01-20
  • 1970-01-01
  • 2022-11-19
  • 1970-01-01
  • 2018-12-16
相关资源
最近更新 更多