首页 > 解决方案 > 2x 嵌套函数中的访问列表

问题描述

def get_html(url):
    response = urllib.request.urlopen(url)
    return response.read()


def parse_main(html):
    webpage = BeautifulSoup(html, features="html.parser")
    table = webpage.find('table', id='itemList')

    for a_tag in table.find_all('a', class_='all'):
        parse_movie(get_html('https://www.somerandommovieswebsite.com' + a_tag['href']))


def parse_movie(html):
    web_page = BeautifulSoup(html, features="html.parser")
    info = web_page.find('h1', class_="moviename")
    movies.append(info.text)


def main():
    movies = []
    parse_main(get_html('https://www.somerandommovieswebsite.com'))
    print(movies)


if __name__ == '__main__':
    main()

如何访问嵌套在parse_main中的parse_movie中的电影列表(在 main() 函数中定义)。由于“未解决的参考'电影' ”错误,无法将任何内容附加到列表中。使用非本地没有帮助

标签: pythonpython-3.x

解决方案


我认为您既不应该在这里使用全局变量,也不应该将其作为参数传递:

def get_html(url):
    response = urllib.request.urlopen(url)
    return response.read()


def parse_main(html):
    movies = []
    webpage = BeautifulSoup(html, features="html.parser")
    table = webpage.find('table', id='itemList')

    for a_tag in table.find_all('a', class_='all'):
        movies.append(
            parse_movie(get_html('https://www.somerandommovieswebsite.com' + a_tag['href']))
        )
    return movies


def parse_movie(html):
    web_page = BeautifulSoup(html, features="html.parser")
    info = web_page.find('h1', class_="moviename")
    return info.text


def main():
    movies = parse_main(get_html('https://www.somerandommovieswebsite.com'))
    print(movies)


if __name__ == '__main__':
    main()

推荐阅读