Python 2.7 BeautifulSoup Python如何在函数中以列表形式返回for循环中的所有值
我有一个带for循环的函数。它遍历列表并将每个值打印到控制台。Python 2.7 BeautifulSoup Python如何在函数中以列表形式返回for循环中的所有值,python-2.7,beautifulsoup,Python 2.7,Beautifulsoup,我有一个带for循环的函数。它遍历列表并将每个值打印到控制台。 我想在函数的末尾放一个return语句,这样当我调用函数时,就可以返回所有的值。 我想我需要把它作为一个列表返回 我的职能是: def extract_header_from_summary_from_report_htmltestrunner(): filename = (r"C:\temp\selenium_report\ClearCore501_Automated_GUI_TestReport.html") ht
我想在函数的末尾放一个return语句,这样当我调用函数时,就可以返回所有的值。 我想我需要把它作为一个列表返回 我的职能是:
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循环返回每个值
for循环打印出以下内容:
Count Pass Fail Error
75 75 0 0
谢谢,Riaz是什么阻止了你创建一个空列表并附加到它上面的呢
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
您可以生成每个字符串:
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]])
然后调用列表(从\u摘要中提取\u头\u从\u报告中提取\u htmlestrunner())
或迭代生成器函数:
for row in extract_header_from_summary_from_report_htmltestrunner():
# use each row