如何选择一个特定的表并使用beauthoulsoup打印它的数据

2024-09-30 05:31:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码,我用它从一个名为ssllabs,com的站点获取结果

from bs4 import BeautifulSoup
import requests
req  = requests.get("https://www.ssllabs.com/ssltest/analyze.html?d=drtest.test.sentinelcloud.com")
data = req.text
soup = BeautifulSoup(data)
report_tables=soup.find_all('table',class_='reportTable')
print report_tables

这将返回以下表格:

My data is in the table indicated with arrorow

现在我的数据在我指定的表中。这个表内部的结构看起来像

^{pr2}$

我需要进入“tbody”并提取所有tableLeft值并将它们放入一个列表中。 我的问题:

1. How to select that particular reportTable at line 493 in picture.
2. How to extract the values (TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384.......................) and put in LIST

Tags: toinimportreportcomtablesdatatls
1条回答
网友
1楼 · 发布于 2024-09-30 05:31:02

稍微扩展@furas的注释,因为report_tables[4]假设它永远是第五个表:

req = requests.get("https://www.ssllabs.com/ssltest/analyze.html?d=drtest.test.sentinelcloud.com")
data = req.text
soup = BeautifulSoup(data)

for found_table in soup.find_all('table', class_='reportTable'):
    if 'Cipher Suites' in found_table.get_text():
        values = found_table.find_all('td', class_='tableLeft')
        entries = []
        for row in values:
            entries.append(row.get_text())
        print entries

检查“密码套件”(如果需要,可以使用更完整的标题)可以帮助您更一致地获得正确的表。在

您可以简单地使用values作为输出,但是使用get_text()可以帮助我们删除一些您可能不需要的html。entries将包含您需要的值,但是您可能需要查看像strip这样的函数来清除结果中的空白。在

产生的结果:

^{pr2}$

编辑:要根据@padraickunningham的注释扩展此值,我们可以删除空白并返回第一个值,如下所示:

for found_table in soup.find_all('table', class_='reportTable'):
    if 'Cipher Suites' in found_table.get_text():
        vals = [td.text.split()[0] for td in found_table.select("td.tableLeft")]
        print vals
        break

相关问题 更多 >

    热门问题