如何仅使用BeautifulSoup打印某些文本

时间:2011-11-02 04:18:00

标签: python beautifulsoup

我正在尝试使用BeautifulSoup为城市政府提取一些财务数据(必须从pdf转换文件)。我只想将数据作为csv文件获取,然后我将在Excel或SAS中进行分析。我的问题是我不想打印“& nbsp;”这是在原始HTML中,只是数字和行标题。关于如何在不使用正则表达式的情况下执行此操作的任何建议?

以下是我正在查看的html示例。接下来是我的代码(目前只是在概念模式的证明,需要证明我可以在继续之前获得干净的数据)。 Python和编程新手,所以感谢任何帮助。

<TD class="td1629">Investments (Note 2)</TD>

<TD class="td1605">&nbsp;</TD>

<TD class="td479">&nbsp;</TD>

<TD class="td1639">-</TD>

<TD class="td386">&nbsp;</TD>

<TD class="td116">&nbsp;</TD>

<TD class="td1634">2,207,592</TD>

<TD class="td479">&nbsp;</TD>

<TD class="td1605">&nbsp;</TD>

<TD class="td1580">2,207,592</TD>

<TD class="td301">&nbsp;</TD>

<TD class="td388">&nbsp;</TD>

<TD class="td1637">2,882,018</TD>

CODE

import htmllib
import urllib
import urllib2
import re
from BeautifulSoup import BeautifulSoup

CAFR = open("C:/Users/snown/Documents/CAFR2004 BFS Statement of Net Assets.html", "r")

soup = BeautifulSoup(CAFR)

assets_table = soup.find(True, id="page_27").find(True, id="id_1").find('table') 

rows = assets_table.findAll('tr')    
for tr in rows:    
  cols = tr.findAll('td')    
  for td in cols:    
    text = ''.join(td.find(text=True))
    print text+"|",    
  print

1 个答案:

答案 0 :(得分:2)

soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES)

它将&nbsp;和其他html实体转换为适当的字符。

将其写入csv文件:

>>> import csv
>>> import sys
>>> csv_file = sys.stdout
>>> writer = csv.writer(csv_file, delimiter="|")
>>> soup = BeautifulSoup("<tr><td>1<td>&nbsp;<td>3",
...                      convertEntities=BeautifulSoup.HTML_ENTITIES)
>>> writer.writerows([''.join(t.encode('utf-8') for t in td(text=True))
...                   for td in tr('td')] for tr in soup('tr'))
1| |3

我已使用t.encode('utf-8'),因为&nbsp;被转换为非ascii U+00A0(不间断空格)字符。