使用Python BeautifulSoup解析HTML表

Kei*_*ith 5 html python beautifulsoup

我试图使用BeautifulSoup来解析我上传到http://pastie.org/8070879的html表以便将三列(0到735,0.50到1.0和0.5到0.0)作为列表.为了解释原因,我希望整数0-735为键,十进制数为值.

通过阅读关于SO的许多其他帖子,我提出了以下内容,这些内容并未接近创建我想要的列表.它所做的就是在表格中显示文字,如图所示http://i1285.photobucket.com/albums/a592/TheNexulo/output_zps20c5afb8.png

from bs4 import BeautifulSoup

soup = BeautifulSoup(open("fide.html"))
table = soup.find('table')

rows = table.findAll('tr')

for tr in rows:
  cols = tr.findAll('td')
  for td in cols:
     text = ''.join(td.find(text=True))
     print text + "|",
  print 
Run Code Online (Sandbox Code Playgroud)

我是Python和BeautifulSoup的新手,所以请温柔地对待我!谢谢

Pau*_*McG 3

像 BeautifulSoup 这样的 HTML 解析器假定您想要的是一个反映输入 HTML 结构的对象模型。但有时(就像在本例中)该模型的弊大于利。Pyparsing 包含一些 HTML 解析功能,这些功能比仅使用原始正则表达式更强大,但在其他方面以类似的方式工作,让您定义感兴趣的 HTML 片段,并忽略其余部分。这是一个解析器,可以读取您发布的 HTML 源代码:

from pyparsing import makeHTMLTags,withAttribute,Suppress,Regex,Group

""" looking for this recurring pattern:
          <td valign="top" bgcolor="#FFFFCC">00-03</td>
          <td valign="top">.50</td>
          <td valign="top">.50</td>

    and want a dict with keys 0, 1, 2, and 3 all with values (.50,.50)
"""

td,tdend = makeHTMLTags("td")
keytd = td.copy().setParseAction(withAttribute(bgcolor="#FFFFCC"))
td,tdend,keytd = map(Suppress,(td,tdend,keytd))

realnum = Regex(r'1?\.\d+').setParseAction(lambda t:float(t[0]))
integer = Regex(r'\d{1,3}').setParseAction(lambda t:int(t[0]))
DASH = Suppress('-')

# build up an expression matching the HTML bits above
entryExpr = (keytd + integer("start") + DASH + integer("end") + tdend + 
                    Group(2*(td + realnum + tdend))("vals"))
Run Code Online (Sandbox Code Playgroud)

该解析器不仅挑选出匹配的三元组,还提取起始端整数和实数对(并且在解析时已经从字符串转换为整数或浮点数)。

看看这个表,我猜你实际上想要一个使用像 700 这样的键的查找,并返回一对值 (0.99, 0.01),因为 700 属于 620-735 的范围。这段代码搜索源 HTML 文本,迭代匹配的条目并将键值对插入到字典查找中:

# search the input HTML for matches to the entryExpr expression, and build up lookup dict
lookup = {}
for entry in entryExpr.searchString(sourcehtml):
    for i in range(entry.start, entry.end+1):
        lookup[i] = tuple(entry.vals)
Run Code Online (Sandbox Code Playgroud)

现在尝试一些查找:

# print out some test values
for test in (0,20,100,700):
    print (test, lookup[test])
Run Code Online (Sandbox Code Playgroud)

印刷:

0 (0.5, 0.5)
20 (0.53, 0.47)
100 (0.64, 0.36)
700 (0.99, 0.01)
Run Code Online (Sandbox Code Playgroud)