python - 如何从 BeautifulSoup ( Python ) 中的表中获取第一个子表行

标签 python beautifulsoup python-requests

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

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

我只想要 JOHNSON,因为他是第一个 child 。 我的 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

最佳答案

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

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

关于python - 如何从 BeautifulSoup ( Python ) 中的表中获取第一个子表行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31554704/

相关文章:

python - 使用 BeautifulSoup 输出 <br> 而不是 <br/>

python - 如何使用 BeautifulSoup 将标签内容从一个 soup 移动到模板 soup

Python 请求,如何为传出流量指定端口?

python - 使用 python requests 模块登录基于 WordPress 的网站

python - 矩阵 QR 分解算法

python - 显示上传/选择的图像而不将其保存在 Django 的数据库中

python - sqlalchemy操作错误: (OperationalError) unable to open database file None None

python - Django 的 LiveServerTestCase 总是由于地址冲突而失败......尽管地址似乎是免费的

Python:解析 SGML

python - 无法将附件正确上传到 Azure DevOps API(0kb 结果)