Python TypeError:只能将列表(不是“str”)连接到列表

Ria*_*ani 2 beautifulsoup python-2.7

我有一个方法,它使用 Beautifulsoup 从 HTML 文件中的标签返回文本列表。当我调用该方法时,我将从该方法返回的值保存到一个变量中。我认为是一个字符串变量。
我再次调用该方法并将返回值存储到不同的字符串变量中。我想连接这两个字符串,以便我可以在换行符上打印每个字符串。然后,我可以将其添加到我的电子邮件例程中,以便它将值打印到电子邮件消息中。

我收到错误:

   Traceback (most recent call last):
  File "E:/test_runners/selenium_regression_test_5_1_1/ClearCore - Regression Test/Email/email_selenium_report.py", line 43, in <module>
    print rows_part1 + "/n" + rows_part2
TypeError: can only concatenate list (not "str") to list
Run Code Online (Sandbox Code Playgroud)

我的方法实现是:

def extract_data_from_report3(filename):
    html_report_part = open(filename,'r')
    soup = BeautifulSoup(html_report_part, "html.parser")
    th = soup.find_all('th')
    td = soup.find_all('td')

    headers = [header.get_text(strip=True) for header in soup.find_all("th")]
    rows = [dict(zip(headers, [td.get_text(strip=True) for td in row.find_all("td")]))
        for row in soup.find_all("tr")[1:-1]]
    print(rows)
    return rows
Run Code Online (Sandbox Code Playgroud)

调用方法如下:

rows_part1 =  report.extract_data_from_report3(r"E:\test_runners\selenium_regression_test_5_1_1\TestReport\SeleniumTestReport_part1.html")
print "part1 = "
print rows_part1

rows_part2 =  report.extract_data_from_report3(r"E:\test_runners\selenium_regression_test_5_1_1\TestReport\SeleniumTestReport_part2.html")
print "part2 = "
print rows_part2

print rows_part1 + "/n" + rows_part2
Run Code Online (Sandbox Code Playgroud)

rows_part1 中的值为:

 part1 = 
[{u'Success': u'219', u'Skip': u'0', u'Error': u'9', u'Fail': u'1', u'Total': u'229', u'Class': u'Regression_TestCase.RegressionProject_TestCase2.RegressionProject_TestCase2'}]
Run Code Online (Sandbox Code Playgroud)

rows_part2 中的值是:

 part2 = 
[{u'Success': u'21', u'Skip': u'0', u'Error': u'10', u'Fail': u'5', u'Total': u'230', u'Class': u'Regression_TestCase.RegressionProject_TestCase2.RegressionProject_TestCase2'}]
Run Code Online (Sandbox Code Playgroud)

我想打印出rows_part 1 的值,然后在换行符上打印出rows_part2 的值。我正在连接它,以便我可以将一个变量放在电子邮件正文中,该变量将打印出该值。

或者如何从列表中提取内容并将其附加到字符串变量?然后我可以打印出字符串变量。

Owe*_*pel 6

首先,在 Python 中,您不必声明变量类型,它是在后台分配的。这让您对变量类型感到困惑。

返回一个列表

[...]

我认为一个字符串变量

您的打印语句试图打印一个list类型对象,然后是一个新行,然后是另一个list类型对象。您的问题来自中间的“\n”。

连接两个字符串是可能的: str1 + str2

连接两个列表是可能的: list1.append(list2)

但是将字符串连接到列表(或将列表连接到字符串)不是!您需要做的是将列表对象转换为字符串(该列表的)。

print str(rows_part1) + "/n" + str(rows_part2)
Run Code Online (Sandbox Code Playgroud)

应该管用。