Search code examples
pythonpython-3.xnameerror

Python3 - Code stopped to work and shows name error


I have the following code that I always run on my server (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")

Few weeks ago, the code has stopped to work and begin to show this error:

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

NameError: name 'linkdown' is not defined

I really cannot understand what happened, since the code was not modified and always worked correctly.

Thank in advance for the help!


Solution

  • The issue with your error is that this line:

    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')
    

    Is not doing anything in case linkdown actually fails, and the variable linkdown is not created, hence the error:

    NameError: name 'linkdown' is not defined

    Try to add:

    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
    

    Additionaly, it might be better to test for existence:

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