2017-06-11 49 views
1

我目前正在得到A,A,B,B的输出而不是A,B,A,B。在循环中合并Python数组?

我真的想将每个表头的值与每个表数据元素(如字典)相关联。

import requests 
from bs4 import BeautifulSoup 

courseCode = "IFB104" 
page = requests.get("https://www.qut.edu.au/study/unit?unitCode=" +  courseCode) 

soup = BeautifulSoup(page.content, 'html.parser') 
table = soup.find_all(class_='table assessment-item') 

numOfTables = 0 
tableDataArray = [] 

for tbl in table: 
    numOfTables = numOfTables + 1 
    tableDataArray += [tbl.find_all('th'),tbl.find_all('td')] 
+0

您能否提供一个表格的例子,以及您期望的输出是什么? –

+0

目前,它打印'3 [名称,说明,加权,截止日期,内部或外部,集团或个人,涉及到学习成果],[​​#3 :测验/测验,​​每周测验。每周在讲座中您将介绍用于解决技术问题的计算原理。您对这些技术的理解将通过每周在线测验和测试进行测试,​​25 & percnt;,​​整个学期,​​内部,​​个人,​​1,2]' – yeeeeee

+0

它打印出所有标签从该表(在整个HTML页表三选一),然后将所有的​​标签)。我想制作一本词典(我最初说的是数组,但字典更好),将每个与每个​​联系起来。这样,我可以打电话给评估的名称,并返回“#3:测验/测试”,或称重,并获得“25%”。 – yeeeeee

回答

1

如果我理解正确的话,你需要使用字典,而不是名单:

import requests 
from bs4 import BeautifulSoup 

courseCode = "IFB104" 
page = requests.get("https://www.qut.edu.au/study/unit?unitCode=" + courseCode) 

soup = BeautifulSoup(page.content, 'html.parser') 
table = soup.find_all(class_='table assessment-item') 

numOfTables = 0 
tableFormatted1 = [] 
tableFormatted2 = {} 

for tbl in table: 
    numOfTables = numOfTables + 1 
    keys = tbl.find_all('th') 
    values = tbl.find_all('td') 
    new_data = dict(zip(keys, values)) 

    # Method 1 
    tableFormatted1.append(new_data) 

    # Method 2 
    for k, v in new_data.items(): 
     if k in tableFormatted2: 
      tableFormatted2[k].append(v) 
     else: 
      tableFormatted2[k] = [v] 

print('List of dictionaries') 
print(tableFormatted1) 
print('') 

print('Dictionary with list') 
print(tableFormatted2) 

编辑:

tbl每次迭代的覆盖已经完成迭代。所以,有必要改变结构。我刚刚提供了两种方法。

+0

几乎完美!除了我意识到我需要为所有三张桌子做,而不仅仅是一张桌子。我原来的帖子在我输入'tableDataArray = ...'而不是'+ ='时出错。它应该遍历3个表格......分解在,​​级别。 – yeeeeee

+0

好的。只需编辑。 – Rafael

+0

但有一个问题。密钥是相同的('name'可以是'Portfolio','Exam(写)'或'Quiz/Test')。你需要一个包含所有值的列表的密钥吗? – Rafael