-3

I seem to have declared target as the input from the user. When trying to run this script with -t google.com -o test I still get the error

NameError: name 'target' is not defined

even though print('Input file is ', target) returns google.com.

What am I doing wrong?

#!usr/bin/env python3

import sys, getopt
from urllib import request

def main(argv):
   target = ''
   outputfile = ''
   try:
      opts, args = getopt.getopt(argv,"ht:o:",["target=","ofile="])
   except getopt.GetoptError:
      print('thmscraper.py -t <target address> -o <outputfile>')
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print('thmscraper.py -t <target address> -o <outputfile>')
         sys.exit()
      elif opt in ("-t", "--target"):
         target = arg
      elif opt in ("-o", "--ofile"):
         outputfile = arg


   print('Input file is ', target)
   print('Output file is ', outputfile)


if __name__ == "__main__":
   main(sys.argv[1:])

from bs4 import BeautifulSoup
html = request.urlopen(target).read().decode('utf8')
soup = BeautifulSoup(html, 'html.parser')
title = soup.find('title')

print(title)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
numpty
  • 1
  • 1
  • related question: https://stackoverflow.com/questions/4693120/use-of-global-keyword-in-python – AcaNg Sep 11 '21 at 09:32
  • @AcaNg not really related because there are no global variables involved here (which is a good thing). – mkrieger1 Sep 11 '21 at 09:32
  • @mkrieger1 i agree, but the error is explained in the answer provided there as an example. and just in case the OP wants to use global keyword rather than put code inside `main()` (i don't recommend it and i think your answer is a better approach). – AcaNg Sep 11 '21 at 09:36

1 Answers1

4

target is a local variable inside the main function, but you are trying to use it outside the function in the module-level code:

html = request.urlopen(target).read().decode('utf8')

It seems to me as if the last 3 lines should be part of the main function as well (and the bs4 import should be at the top with all other imports).

mkrieger1
  • 19,194
  • 5
  • 54
  • 65