所以我要使用BS4进行报废,我想将值的每一行都放在不同的列表中,然后将所有这些列表合并到一个列表中。
目前我正在这样做:
team_values = []
teams_values = []
for team in team_rows:
team_data = team.find_all("td")
for data in team_data:
if hasattr(data, 'attrs') and 'data-val' in data.attrs:
#print("\t{}".format(data.attrs['data-val']))
value = data.attrs['data-val']
#print(value)
team_values.append(value)
#print(team_values)
teams_values.append(team_values)
但是它将返回一个值列表,而不是列表列表。有什么帮助吗?
答案 0 :(得分:1)
您的缩进在最后一行关闭,您需要在进入第二个team_values
循环之前重置for
teams_values = []
for team in team_rows:
team_data = team.find_all("td")
team_values = [] # reset here
for data in team_data:
if hasattr(data, 'attrs') and 'data-val' in data.attrs:
#print("\t{}".format(data.attrs['data-val']))
value = data.attrs['data-val']
#print(value)
team_values.append(value)
#print(team_values)
teams_values.append(team_values) # add indentation here
答案 1 :(得分:1)
尝试一下
teams_values = []
for team in team_rows:
team_values = []
team_data = team.find_all("td")
for data in team_data:
if hasattr(data, 'attrs') and 'data-val' in data.attrs:
#print("\t{}".format(data.attrs['data-val']))
value = data.attrs['data-val']
#print(value)
team_values.append(value)
#print(team_values)
teams_values.append(team_values)
在将team_values
的内容附加到teams_values
后,您并没有“重置”该内容。
PS:在我发布此答案时,其他两个都没有指出此“重置”。
答案 2 :(得分:1)
teams_values = []
for team in team_rows:
team_data = team.find_all("td")
team_values = []
for data in team_data:
if hasattr(data, 'attrs') and 'data-val' in data.attrs:
#print("\t{}".format(data.attrs['data-val']))
value = data.attrs['data-val']
#print(value)
team_values.append(value)
#print(team_values)
teams_values.append(team_values)
答案 3 :(得分:0)
我认为您的循环逻辑只需要很小的改变:
teams_values = []
for team in team_rows:
team_data = team.find_all("td")
team_values = []
for data in team_data:
if hasattr(data, 'attrs') and 'data-val' in data.attrs:
#print("\t{}".format(data.attrs['data-val']))
value = data.attrs['data-val']
#print(value)
team_values.append(value)
#print(team_values)
teams_values.append(team_values)
print teams_values # should show what you want