我试图以列格式输出数据。
我尝试了两种方法,第一种用于测试目的:在数据集中调用已识别的值(在测试期间限制运行时间)。第二种方法利用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没有产生相同的输出列模式,或者我可能对它做些什么?谢谢
发布于 2020-06-04 18:18:03
我知道这不酷,但我第二天一早就想好了,我想我只是需要重新审视一下。我需要像方法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)发布于 2020-06-04 08:57:18
首先尝试获取所需的表,然后是表行 (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)https://stackoverflow.com/questions/62187145
复制相似问题