我有以下问题:当 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/