使用Beautifulsoup解析后写入csv会导致分隔值或空输出文件

时间:2017-04-11 21:01:55

标签: python html csv beautifulsoup

<table class="table_grid">
    <thead>
        <tr>
            <th>Name</th>
            <th>User Name</th>
            <th>Role</th>
            <th>Branch</th>
            <th>Actions</th>

        </tr>
    </thead>
    <tbody>

                <tr>
                    <td>First Name1</td>
                    <td>email1@mail.com</td>
                    <td>Processor</td>

                    <td></td>   

                                <td><a href="/Account/EditUser?id=4c4e6455-7d27-4abf-93c9-5584f09674d5">Edit</a></td>

                </tr>

                <tr>
                    <td>First Name2</td>
                    <td>email2@mail.com</td>
                    <td>Officer</td>

                    <td></td>   

                                <td><a href="/Account/EditUser?id=267e90eb-6fa4-4286-88d9-738913cdd7ea">Edit</a></td>

                </tr>

    </tbody>
</table>

我正在尝试解析此表中的文本并将其写入csv文件。它写入csv但每个字母都以新列结尾。 | F | I | R | S | T |当我在寻找|首先|。

soup = BeautifulSoup(browser.page_source, 'html.parser')

table = soup.find('table', attrs={'class':'table_grid'})

with open('test1.csv', 'w', newline='') as outfile:
    writer = csv.writer(outfile)
    for body in table.findAll('tr'):
        rows = body.getText()
        writer.writerow(rows)

这是我的代码。在此处查看类似问题,我尝试使用以下方法解决此问题:

writer.writerow([rows])

然而,这导致了一个空白的csv文件。知道我在这里做错了吗?

1 个答案:

答案 0 :(得分:1)

我认为您打算将每个单元格写入其自己的列

with open('test1.csv', 'w', newline='') as outfile:
    writer = csv.writer(outfile)
    for row in table('tr'):
        writer.writerow([cell.get_text(strip=True) for cell in row(['td', 'th'])])

请注意,我在这里使用了一些快捷方式 - table('tr')是另一种简洁的方式table.find_all('tr')

此外,将HTML表格转储为CSV的另一种方法是使用pandas库,特别是 - .read_html().to_csv()方法。