You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在函数与循环外部获取全局变量prod的所有值?

问题分析与解决

原代码片段:

soup = BeautifulSoup(filehandle, "html.parser")
soup = soup.find('ul', class_='listing')
thdr = soup.find('div', class_='heading')

if (chk == "n"):
   
while (thdr != None):
for thdr in thdr:
   global prod      
   temp = thdr.string
   prod = thdr.string
   print prod

你遇到的核心问题是prod是单个字符串变量,每次循环都会用新的thdr.string覆盖掉之前的值——哪怕声明成global也没用,global只是让函数能修改外部的prod变量,但本质上它还是单个值,存不了多个内容。

修正方案

把prod改成列表类型,循环时把每个值追加进去,就能保存所有内容了,同时顺便修正原代码里的语法错误(缩进、print语法、空if块):

# 先在函数外部定义全局列表
prod = []

def your_parse_function(filehandle, chk):
    global prod
    soup = BeautifulSoup(filehandle, "html.parser")
    listing_ul = soup.find('ul', class_='listing')
    # 用find_all获取所有匹配的heading元素,原代码的find只会拿第一个
    thdr_list = listing_ul.find_all('div', class_='heading')

    if chk == "n":
        # 这里补全你需要的逻辑,暂时用pass占位
        pass

    # 遍历所有heading元素
    for thdr in thdr_list:
        if thdr.string:  # 避免无文本的元素返回None导致报错
            prod.append(thdr.string)
            print(thdr.string)  # Python3中print需要加括号

# 调用函数后,在外部打印整个列表
your_parse_function(your_file_handle, "n")
print(prod)  # 这里就能看到所有保存的值了

关键说明

  1. 用列表prod = []替代单个字符串变量,每次循环用append()添加新值,不会覆盖之前的内容。
  2. 原代码里soup.find('div', class_='heading')只会返回第一个匹配的元素,要获取所有同类型元素需要用find_all,否则循环逻辑不成立。
  3. 修复了Python对缩进敏感的语法错误,以及Python3中print必须加括号的问题。
  4. 增加了if thdr.string的判断,避免某些没有文本内容的元素返回None,导致列表混入无效值。

内容的提问来源于stack exchange,提问作者Sam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 07:22:15