Python脚本报NameError错误:已声明target变量但提示未定义
问题原因及解决方案
核心错误原因
target是main()函数内部定义的局部变量,仅在main()函数作用域内生效,函数外部的全局作用域无法直接访问。
你代码里的网页解析逻辑(导入BeautifulSoup及后续代码)写在全局作用域,执行时全局作用域没有定义target变量,因此抛出NameError。之前的print('Input file is ', target)能正常输出,是因为这行代码本身就在main()函数内部,可以访问同作用域的局部变量。
修复方案
推荐把所有网页解析逻辑挪到main()函数内部,避免全局变量污染,修改后的完整代码如下:
#!usr/bin/env python3 import sys, getopt from urllib import request from bs4 import BeautifulSoup 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) # 网页解析逻辑移到main函数内部 html = request.urlopen(target).read().decode('utf8') soup = BeautifulSoup(html, 'html.parser') title = soup.find('title') print(title) if __name__ == "__main__": main(sys.argv[1:])
内容的提问来源于stack exchange,提问作者numpty
相关产品推荐
相关产品推荐

