Riaz Ladhani
Riaz Ladhani

Reputation: 4062

BeautifulSoup my for loop is printing the data in separate lines. How do i print it in 1 line

I have the following sample HTML table from a html file.
I am trying to print the text from the

<table>
        <tr>
            <th>Class</th>
            <th class="failed">Fail</th>
            <th class="failed">Error</th>
            <th>Skip</th>
            <th>Success</th>
            <th>Total</th>
        </tr>
            <tr>
                <td>Regression_TestCase.RegressionProject_TestCase2.RegressionProject_TestCase2</td>
                <td class="failed">1</td>
                <td class="failed">9</td>
                <td>0</td>
                <td>219</td>
                <td>229</td>
            </tr>
        <tr>
            <td><strong>Total</strong></td>
            <td class="failed">1</td>
            <td class="failed">9</td>
            <td>0</td>
            <td>219</td>
            <td>229</td>
        </tr>
    </table>

My for loop is:

def extract_data_from_report():
    html_report = open(r"E:\projects\ClearCore\ClearCore Regression\selenium_regression_test_5_1_1\TestReport\SeleniumTestReport.html",'r').read()
    soup = BeautifulSoup(html_report, "html.parser")
    print soup.find_all('th')
    print soup.find_all('td')

    for item in soup.find_all('th'):
        print item.text

The output is:

Class
Fail
Error
Skip
Success
Total

I would like the output to be like this:

Class Fail Error Skip Success Total

How do i print it all in 1 line?

Thanks, Riaz

Upvotes: 1

Views: 194

Answers (1)

amiller27
amiller27

Reputation: 506

By default, Python adds a newline every time you have a print statement. If you add a comma at the end of your list of items to print, Python will instead add a space at the end with no newline. What you need to do is this:

Replace

print item.text

with

print item.text,

You will also need a single print after everything in the list is printed (i.e. at the very end of your function). This will put that terminating newline at the end of your list.

Upvotes: 1

Related Questions