【问题标题】:How to parse HTML and get table ids using Python如何使用 Python 解析 HTML 并获取表格 ID
【发布时间】:2021-04-16 17:33:23
【问题描述】:

我正在寻找解析 html 并使用 python 获取表 id 列表。

我有一个包含多个表格的以下格式的 HTML 文档:

我正在尝试抓取并获取表格 ID 的页面 - https://docs.aws.amazon.com/workspaces/latest/adminguide/workspaces-port-requirements.html

<html>
<div class="table-container">
  <div class="table-contents disable-scroll">
     <table id="w345aab9c13c11b5"> # this is table id for below table name
        <thead>
           <tr>
              <th class="table-header" colspan="100%">
                 <div class="title">Domains and IP addresses to add to your allow list</div> # I need to look for this table name and get the table id associated with it
              </th>
           </tr>
        </thead>
        <tbody>
          ...
     </tbody>
    </table>
  </div>
</div>
<div class="table-container">
  <div class="table-contents disable-scroll">
     <table id="w345aab9c13c13b2">
        <thead>
           <tr>
              <th class="table-header" colspan="100%">
                 <div class="title">Domains and IP Addresses to Add to Your Allow List for PCoIP</div>
              </th>
           </tr>
           <tr>
          ...
           </tr>
        </thead>
        <tbody>
          ...
     </tbody>
    </table>
  </div>
</div>
...
</html>

我需要检查div标签中的匹配值并获取与之关联的表ID

我是 python 新手,任何关于如何处理这个问题或解决方案的建议都会很有帮助。

【问题讨论】:

  • 答案取决于您使用什么来获取 HTML。告诉我们你有什么。
  • 感谢您的回复,请查看更新后的代码。 @JustinEzequiel

标签: python python-3.x dataframe web-scraping html-parsing


【解决方案1】:

您可以使用 BeautifulSoup 获取 ID:

import requests
from bs4 import BeautifulSoup

url = 'http://docs.aws.amazon.com/workspaces/latest/adminguide/workspaces-port-requirements.html'

resp = requests.get(url)

soup = BeautifulSoup(resp.content, 'html.parser')

for t in soup.select('table[id]'):
    if 'Domains and IP Addresses to Add to Your Allow List' in t.getText():
        print(t.attrs['id'])

我相信您可以弄清楚如何将其合并到您的代码中。

【讨论】:

  • 我需要查找div 标记内的表名并获取与之关联的表ID。例如。查找Domains and IP addresses to add to your allow list 并获取其 ID
  • 您真的不应该在发布答案后更改要求,而是检查编辑后的答案。
  • 我已经提到了问题中的要求。感谢您更新您的答案
  • “我已经提到了问题中的要求。” - 不,你没有。您只提到您需要表 ID。没有提及文本“要添加到您的允许列表的域和 IP 地址”
  • 抱歉不清楚。我在第一个代码示例的line 8 中提到了一点,并且在问题正文中“我需要检查 div 标签中的匹配值并获取与之关联的表 id”
猜你喜欢
  • 1970-01-01
  • 2022-08-02
  • 2017-05-18
  • 2017-06-23
  • 2016-12-25
  • 1970-01-01
  • 2015-10-14
  • 2011-01-04
相关资源
最近更新 更多