我正在解析网页中的数据,有时表格中有不需要的回车符,这给我带来了问题。我想删除回车符,但简单的 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/