全局变量在函数外不起作用

Global variable doesn't work outside the function

我需要你的帮助。为什么我会收到此错误? 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)

您还没有 运行 您的函数 - 因此 运行ning 代码从未见过您的全局语句。

要使您的代码正常工作,请先调用您的函数:

get_history_events(...)
print(title)

这是一组供全球使用的优秀示例:https://www.programiz.com/python-programming/global-keyword

感谢大家。固定的。工作正常。