繁体   English   中英

Python For-Loop Output 列模式

[英]Python For-Loop Output Column Patterns

我正在尝试以列格式处理 output 数据。

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

我从中提取数据的每个 HTML 页面都有不可预测的项目数量,这些项目将附加到列表中,因此单独列出它们(如方法 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 Output:

Column 1: a, b, c

Column 2: a, b, c

方法二代码:

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 Output:

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

有人知道为什么方法 2 没有产生相同的 output 列模式或者我可能会怎么做? 谢谢

尝试首先获取所需的,然后是表行(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)

我知道这并不酷,但我第二天早上第一件事就想通了,我想我只是需要重新审视一下。 我需要像方法 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM