2016-08-13 43 views
1

我有一個for循環的函數。它迭代一列表並將每個值打印到控制檯。
我想在函數的末尾加上return語句,所以當我調用函數時,我可以返回所有的值。 我想我需要將它作爲列表返回。BeautifulSoup Python我如何返回我的函數列表中的所有值作爲我的函數中的列表

我的功能是:

def extract_header_from_summary_from_report_htmltestrunner(): 
    filename = (r"C:\temp\selenium_report\ClearCore501_Automated_GUI_TestReport.html") html_report_part = open(filename,'r') 
    soup = BeautifulSoup(html_report_part, "html.parser") 
    table = soup.select_one("#result_table") 
    headers = [td.text for td in table.select_one("#header_row").find_all("td")[1:-1]] 
    print(" ".join(headers)) 
    for row in table.select("tr.passClass"): 
     print(" ".join([td.text for td in row.find_all("td")[1:-1]])) 

我如何將返回在最後,並從返回的每個值的循環?

for循環打印出以下幾點:

Count Pass Fail Error 
75 75 0 0 

感謝,里亞茲

回答

2

是什麼阻止你只是創建一個空的列表,並追加到它?

def extract_header_from_summary_from_report_htmltestrunner(): 
    filename = (r"C:\temp\selenium_report\ClearCore501_Automated_GUI_TestReport.html") html_report_part = open(filename,'r') 
    soup = BeautifulSoup(html_report_part, "html.parser") 
    table = soup.select_one("#result_table") 

    #Create list here... 
    results = [] 

    headers = [td.text for td in table.select_one("#header_row").find_all("td")[1:-1]] 
    print(" ".join(headers)) 

    #Don't forget to append header (if you want) 
    results.append(headers) 

    for row in table.select("tr.passClass"): 
     #Store row string in variable and append before printing 
     row_str = " ".join([td.text for td in row.find_all("td")[1:-1]])) 
     results.append(row_str) 
     print(row_str) 

    return results 
+0

這對我的作品。謝謝你的幫助。 –

1

可以得到每個字符串:

from bs4 import BeautifulSoup 

def extract_header_from_summary_from_report_htmltestrunner(): 
    filename = (r"C:\temp\selenium_report\ClearCore501_Automated_GUI_TestReport.html") html_report_part = open(filename,'r') 
    soup = BeautifulSoup(html_report_part, "html.parser") 
    table = soup.select_one("#result_table") 
    headers = [td.text for td in table.select_one("#header_row").find_all("td")[1:-1]] 
    yield (" ".join(headers)) 
    for row in table.select("tr.passClass"): 
     yield " ".join([td.text for td in row.find_all("td")[1:-1]]) 

然後調用list(extract_header_from_summary_from_report_htmltestrunner())或遍歷發生器功能:

for row in extract_header_from_summary_from_report_htmltestrunner(): 
    # use each row 
相關問題