Python前循环输出列模式

问题描述 投票:0回答:2

我正在尝试以列格式输出数据。

我尝试了两种方法,第一种是用于测试目的;调用数据集中的已标识值(限制测试期间的运行时间)。第二种方法利用for循环从数据集中提取所有数据。但是,第二种方法输出的列模式与我预期的不同。

我要从中提取数据的每个HTML页面都有不可预测的项目数,这些项目将追加到列表中,因此单独对它们进行编号(如方法1中所述)将不起作用。

这里是代码的概述及其结果的显示:

方法1代码:

for num in range(1, 3):
    url = "https://test.com/testid={}".format(num)
    # [. . . ]
    set = soup.find_all('td') # call to pull data
    a = set[0]
    b = set[1]
    c = set[2]
    info = [a,b,c]
    print(info)

方法1输出:

Column 1: a, b, c

Column 2: a, b, c

方法2代码:

for num in range(1, 3):
    url = "https://test.com/testid={}".format(num)
    # [. . . ]
    set = soup.find_all('td') # call to pull data
    info = []
    for data in set:    
        info.append(data)
    print(info)

方法2输出:

Column 1: a, b, c, a, b, c

有人知道为什么方法2不能产生相同的输出列模式,或者我会怎么做吗?谢谢

python csv web-scraping
2个回答
0
投票

尝试首先获取所需的,然后是表行(tr),然后是表数据(td)。

table = soup.find("table") # get the table
table_data = table.tbody.find_all("tr")  # get the table rows (tr)

data = []
for i in table_data[0].find_all("td"): # get the table data (td)
    data.append(i.text)

print(data)

0
投票

我知道这很酷,但是第二天早上我想出了第一件事,我想我只需要重新看一下。我需要按照方法1将数据集细分为列表项,并按照方法2调用所有项。经过一些测试,我发现问题与.append调用有关(我不确定为什么其属性如此它不是按照与手动将值添加到列表中相同的方式对数据进行分段吗?)因此,我制作了一个列表,该列表从头到尾自动跨越以绕过.append调用。像这样:

for num in range(1, 3):
    url = "https://test.com/testid={}".format(num)
    # [. . . ]
    set = soup.find_all('td') # call to pull data
    info = td[0:-1] #segments list items but also calls the full list
    print(info)
© www.soinside.com 2019 - 2024. All rights reserved.