python - 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() 函数中定义)。由于“未解决的参考'电影' ”错误,无法将任何内容附加到列表中。使用非本地没有帮助
解决方案
我认为您既不应该在这里使用全局变量,也不应该将其作为参数传递:
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()
推荐阅读
- java - AWS Lambda 冷启动似乎比它在 Cloud Watch 日志上打印的时间更长 (Init Duration : *)
- regex - Lua:如何在字符串中的两个或多个重复字符之间放置一些东西?
- javascript - 如果一个输入仅包含另一个输入内的值,则将两个文本输入与逗号分隔值进行比较返回 true
- python - 使用 imageai -module 'keras.backend' 进行对象检测没有属性 'get_session'-
- python - 提高熊猫滚动应用的速度
- c# - 调用 Dapper 查询
有时会崩溃 - c++ - 如何使我的向量增长到最初未知的大小?
- mysql - SQL查询的结果给出了奇怪的结果
- azure - Azure Cloud 在版本“secrets-store.csi.k8s.io/v1alpha1”中没有匹配类型“SecretProviderClass”
- react-native - React Navigation:单击底部选项卡导航器时打开抽屉