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

Jos*_*Lee 1 html python tags beautifulsoup

我有以下问题:当html标签之间有空格时,我的代码不会给我输出的文本.

而不是输出:

year|salary|bonus
2005|100,000|50,000
2006|120,000|80,000
Run Code Online (Sandbox Code Playgroud)

我得到了这个:

 |salary|bonus
2005|100,000|50,000
2006|120,000|80,000
Run Code Online (Sandbox Code Playgroud)

未输出文本"年份".

这是我的代码:

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)
Run Code Online (Sandbox Code Playgroud)

问题来自于:

"<td> <p>year</p></td>"
Run Code Online (Sandbox Code Playgroud)

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

Her*_*aaf 5

而不是row.append(''.join(td.find(text=True))),使用:

row.append(''.join(td.text))
Run Code Online (Sandbox Code Playgroud)

输出:

year|salary|bonus
2005|100,000|50,000
2006|120,000|80,000
Run Code Online (Sandbox Code Playgroud)