python3 beautifulsoup 表格指定行_python – 如何使用BeautifulSoup从特定的表中获取所有行?...

本文介绍了如何使用Python的BeautifulSoup库从HTML文档中的特定表格获取所有行。通过找到表格子元素,如``和``,然后遍历``单元格,可以轻松提取表格中的文本值。
摘要由CSDN通过智能技术生成

如果你有一大块HTML来解析BeautifulSoup,这应该很简单.一般的想法是使用findChildren方法导航到你的表,然后你可以使用string属性获取单元格内的文本值.

>>> from BeautifulSoup import BeautifulSoup

>>>

>>> html = """

...

...

...

...

column 1column 2

...

value 1value 2

...

...

...

... """

>>>

>>> soup = BeautifulSoup(html)

>>> tables = soup.findChildren('table')

>>>

>>> # This will get the first (and only) table. Your page may have more.

>>> my_table = tables[0]

>>>

>>> # You can find children with multiple tags by passing a list of strings

>>> rows = my_table.findChildren(['th', 'tr'])

>>>

>>> for row in rows:

... cells = row.findChildren('td')

... for cell in cells:

... value = cell.string

... print "The value in this cell is %s" % value

...

The value in this cell is column 1

The value in this cell is column 2

The value in this cell is value 1

The value in this cell is value 2

>>>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值