您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何使用BeautifulSoup成对提取表数据?

如何使用BeautifulSoup成对提取表数据?

列表理解将使它更容易:

table = soup.find("table", id = "history")
rows = table.findAll('tr')
data = [[td.findChildren(text=True) for td in tr.findAll("td")] for tr in rows]
# data Now contains:
[[u'Google', u'07/11/2001'],
 [u'Apple', u'27/08/2001'],
 [u'Microsoft', u'01/11/1991']]

# If the data may contain extraneous whitespace you can clean it up
# Additional processing Could also be done - but once you hit much more
# complex than this later maintainers, yourself included, will thank you
# for using a series of for loops that call clearly named functions to perform
# the work.
data = [[u"".join(d).strip() for d in l] for l in data]

# If you want to store it joined as name | company
# then simply follow that up with:
data = [u"|".join(d) for d in data]

列表理解基本上是一个for带有聚合的反向循环:

[[td.findNext(text=True) for td in tr.findAll("td")] for tr in rows]

转换为 :

final_list = []
intermediate_list = []

for tr in rows:
    for td in tr.findAll("td")
        intermediate_list.append(td.findNext(text=True))

    final_list.append(intermediate_list)
    intermediate_list = []

data = final_list

粗略地讲-我们不考虑生成而不 建立中间列表的麻烦,因为我现在不能在不弄乱示例的情况下添加生成器。

其他 2022/1/1 18:43:09 有289人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶