python - 在 Python 中使用 BeautifulSoup 从 HTML 中删除回车符

标签 python beautifulsoup

我正在解析网页中的数据,有时表格中有不需要的回车符,这给我带来了问题。我想删除回车符,但简单的 strip() 不起作用。

我有以下代码:

html = """
<table>
<tr>
<td>
Commercial, financial and agricultural</td>
<td>
791
</td>
</tr>
</table>
"""

soup = BeautifulSoup(''.join(html))
table = soup.find('table')

rows = table.findAll('tr')
for tr in rows:
    rowdata = ''
    columns = tr.findAll('td')
    for td in columns:
        cell = ''.join(td.findAll(text=True))
        cell.strip()
        rowdata = rowdata+'|'+cell
    print rowdata

输出为:

|
Commercial, financial and agricultural|
791

我希望输出为: |商业、金融和农业|791

为什么 strip 函数没有删除回车符?

最佳答案

>>> cell = 'text\n'
>>> cell.strip()
'text'
>>> rowdata = '|' + cell
>>> print rowdata
|text

>>> rowdata = '|' + cell.strip()
>>> print rowdata
|text

Strip 正在删除返回值,但 strip 返回一个值。它不会将单元格设置为等于任何内容。试试rowdata = rowdata + '|' + cell.strip() .

关于python - 在 Python 中使用 BeautifulSoup 从 HTML 中删除回车符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10544877/

相关文章:

python - 如何在缩进中使用制表符和空格不一致? | python

python - 如何从列表创建 URL 参数

python - 0-1 Knapsack 2 rows 如何找元素

python - 用另一列 Python Pandas 中的数据替换 NAT 日期

python - 如何使用 python,BeautifulSoup 获取跨度值

python - Python 和 MySQL 的问题

python - 从 Python 列表中删除 BeautifulSoup 标签

python - BeautifulSoup 从 Selenium 已经打开的网页中抓取

python - 从 Investing 中查找并提取 curr_id 号码

python - 如何在 python beautifulsoup 中解析出以下 HTML?