【问题标题】:How to get first child table row from a table in BeautifulSoup ( Python )如何从 BeautifulSoup ( Python ) 中的表中获取第一个子表行
【发布时间】:2015-10-11 19:56:38
【问题描述】:

这是代码和示例结果,我只希望表格的第一列忽略其余部分。 Stackoverflow 上有类似的问题,但没有帮助。

<tr>
<td>JOHNSON</td>
<td> 2,014,470 </td>
<td>0.81</td>
<td>2</td>
</tr>

我只想要 JOHNSON,因为它是第一个孩子。 我的python代码是:

import requests
  from bs4 import BeautifulSoup
 def find_raw():
      url = 'http://names.mongabay.com/most_common_surnames.htm'
      r = requests.get(url)
      html = r.content
      soup = BeautifulSoup(html)
      for n in soup.find_all('tr'):
          print n.text
  
  find_raw()

我得到了什么:

SMITH 2,501,922 1.0061
JOHNSON 2,014,470 0.812

【问题讨论】:

  • 您的问题并不完全清楚。如果你得到每个 tr 的第一个子 td,你想要第一个 column 而不是第一个 row。你能澄清一下吗?
  • 已编辑。确实是专栏

标签: python beautifulsoup python-requests


【解决方案1】:

遍历tr,然后打印第一个td的文本:

for tr in bs4.BeautifulSoup(data).select('tr'):
    try:
        print tr.select('td')[0].text
    except:
        pass

或更短:

>>> [tr.td for tr in bs4.BeautifulSoup(data).select('tr') if tr.td]
[<td>SMITH</td>, <td>JOHNSON</td>, <td>WILLIAMS</td>, <td>JONES</td>, ...]

相关帖子:

【讨论】:

    【解决方案2】:

    您可以找到所有带有find_alltr 标签,然后对于每个trfind(只给出第一个)td。如果存在,则打印它:

    for tr in soup.find_all('tr'):
        td = tr.find('td')
        if td:
            print td
    

    【讨论】:

    • 谢谢,你能解释一下吗?我的意思是如果我只需要迭代第二行或第三行怎么办?
    猜你喜欢
    • 2013-08-16
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 2020-11-03
    • 2018-07-13
    • 1970-01-01
    相关资源
    最近更新 更多