python - 如何在 Python 中使用 BeautifulSoup 删除 HTML 标签之间的空格?

标签 python html tags beautifulsoup

我有以下问题:当 html 标签之间有空格时,我的代码没有给我想要输出的文本。

而不是输出:

year|salary|bonus
2005|100,000|50,000
2006|120,000|80,000

我得到这个:

 |salary|bonus
2005|100,000|50,000
2006|120,000|80,000

不输出文本“year”。

这是我的代码:

from BeautifulSoup import BeautifulSoup
import re


html = '<html><body><table><tr><td> <p>year</p></td><td><p>salary</p></td><td>bonus</td></tr><tr><td>2005</td><td>100,000</td><td>50,000</td></tr><tr><td>2006</td><td>120,000</td><td>80,000</td></tr></table></html>'
soup = BeautifulSoup(html)
table = soup.find('table')
rows = table.findAll('tr')

store=[]

for tr in rows:
    cols = tr.findAll('td')
    row = []
    for td in cols:
        try:
            row.append(''.join(td.find(text=True)))
        except Exception:
            row.append('')
    store.append('|'.join(filter(None, row)))
print '\n'.join(store)

问题出在空间上:

"<td> <p>year</p></td>"

当我从网上提取一些 html 时,有没有办法摆脱那个空间?

最佳答案

代替 row.append(''.join(td.find(text=True))),使用:

row.append(''.join(td.text))

输出:

year|salary|bonus
2005|100,000|50,000
2006|120,000|80,000

关于python - 如何在 Python 中使用 BeautifulSoup 删除 HTML 标签之间的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5733373/

相关文章:

python - 在调用函数时如何防止 GUI 卡住? (PyQT4, Python3)

python - emacs:将 python 空格转换为制表符

javascript - 如何应用 CSS

tags - 如何使页面加载到 anchor 标记?

html - 在 epub 中使用 HTML 与 CSS 进行格式化

python - Pyinstaller exe 文件有多大?

python - 具有多个条件的 xarray.where()

javascript - ReactJS:有一个带有绑定(bind)的类名,而另一个没有绑定(bind)的类名

javascript - 通过 Rotten Tomatoes API 检索电影

html - 我的网站在除 Firefox 之外的所有浏览器中都能正常显示