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

标签 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|当我寻找|First|时。

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 文件。知道我在这里做错了什么吗?

最佳答案

我认为您的意思是将每个单元格写入它自己的列:

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()方法。

关于python - 使用 Beautifulsoup 解析后写入 csv 会导致分离值或空输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43356137/

相关文章:

python - 如何根据谓词对迭代器输出进行分段?

python - 使用 azure 函数时未找到名为 twilio 的模块

html - Flexbox:如何创建我的缩略图以跨越 100% 的容器宽度?

php - csv 文件中的空行

python - 导入错误 : No module named numpy

python - 如何在 django 中使用 python manage.py test 命令运行所有测试

javascript - 通过 javascript 调用更改 onclick 函数时无法发送动态 javascript 参数

javascript - 是否可以使用 EM 在媒体查询中覆盖浏览器的默认字体大小?

javascript - 将文本区域中的 CSV 输入转换为动态表

regex - 删除每行外部分隔符之间的多个分隔符