gpt4 book ai didi

python - 使用 Python BeautifulSoup 解析 HTML 表格

转载 作者:太空狗 更新时间:2023-10-29 15:50:38 24 4
gpt4 key购买 nike

我正在尝试使用 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

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

最佳答案

像 BeautifulSoup 这样的 HTML 解析器假定您想要的是一个反射(reflect)输入 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"))

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

查看该表,我猜您实际上想要一个查找,它会采用像 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)

现在尝试一些查找:

# print out some test values
for test in (0,20,100,700):
print (test, lookup[test])

打印:

0 (0.5, 0.5)
20 (0.53, 0.47)
100 (0.64, 0.36)
700 (0.99, 0.01)

关于python - 使用 Python BeautifulSoup 解析 HTML 表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17256958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com