我需要你的帮助。为什么会出现此错误?title被指定为全局变量,所以我应该打印出"None",对吗?
def get_history_events(requests, BeautifulSoup):
global title, facts
title = facts = None
url = 'https://cs.wikipedia.org/wiki/Hlavn%C3%AD_strana'
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0'}
r = requests.get(url, headers=header).text
soup = BeautifulSoup(r, 'lxml')
table = soup.find('div', class_ = 'mainpage-block calendar-container')
title = table.find('div', class_ = 'mainpage-headline').text
facts = table.find('ul').text
print(title)
# NameError: name 'title' is not defined
您需要首先在全局作用域中声明变量
例如:
title = None
def get_history_events(requests, BeautifulSoup):
global title, facts
title = facts = None
url = 'https://cs.wikipedia.org/wiki/Hlavn%C3%AD_strana'
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0'}
r = requests.get(url, headers=header).text
soup = BeautifulSoup(r, 'lxml')
table = soup.find('div', class_ = 'mainpage-block calendar-container')
title = table.find('div', class_ = 'mainpage-headline').text
facts = table.find('ul').text
print(title)
或者在调用print之前执行您的函数:例如:
def get_history_events(requests, BeautifulSoup):
global title, facts
title = facts = None
url = 'https://cs.wikipedia.org/wiki/Hlavn%C3%AD_strana'
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:88.0) Gecko/20100101 Firefox/88.0'}
r = requests.get(url, headers=header).text
soup = BeautifulSoup(r, 'lxml')
table = soup.find('div', class_ = 'mainpage-block calendar-container')
title = table.find('div', class_ = 'mainpage-headline').text
facts = table.find('ul').text
get_history_events(<imagine your args here>)
print(title)
您还没有运行您的函数,所以运行代码从来没有看到过您的全局语句。
要使代码工作,请首先调用您的函数:
get_history_events(...)
print(title)
以下是一组可供全球使用的优秀示例:https://www.programiz.com/python-programming/global-keyword
感谢大家。固定的工作正常。