python - Python Beautifulsoup htmltable 提取问题
问题描述
我正在尝试从有点非结构化的 html 表中提取数据。HTML表格结构如下(示例数据) -
能够提取数据,但面临“ID”列的问题。“ID”是 2 列的单个标题,该表的结构也不一致。
运行以下代码 -
#Libraries
import urllib3, re
import requests
from bs4 import BeautifulSoup,Comment
import pandas as pd
import numpy as np
import re
group_techniques = []
#Loop through the URLs we loaded above
for b in base_url:
html = requests.get(b).text
soup = BeautifulSoup(html, "html.parser")
#provide the table name we want to scrape
group_table = soup.find('table', {"class" : "table techniques-used table-bordered mt-2"})
#try clause to skip any url with missing/empty tables
try:
#loop through table, grab each of the 5 columns shown
for row in group_table.find_all('tr'):
cols = row.find_all('td')
if len(cols) == 5:
group_techniques.append((b, cols[0].text.strip(), cols[1].text.strip(), cols[2].text.strip(),
cols[3].text.strip(),cols[4].text.strip()))
except: pass
#convert output to new array
group_tech_array = np.asarray(group_techniques)
#convert array to dataframe
df_grp_tech = pd.DataFrame(group_tech_array)
#rename columns, check output
df_grp_tech.columns = ['Domain','Tech_ID','sub_id','Name','Use']
当我们比较实际输出与预期输出时 -
- 我们缺少原始 html 表中的第 3 行(T1560)
- 我们从原始 html 表中缺少第 5 行(T1059)这是因为复杂的表结构
提取后的实际表结构
预期的表结构
** HTML 表格 ** 这是链接“表格 - 使用的技术”
解决方案
至少在这种情况下,使用熊猫要简单得多:
tables = pd.read_html('https://attack.mitre.org/groups/G0004/')
tables[1]
就是这样。输出是您的目标表。
推荐阅读
- vue.js - Vue mixin的数据出现在两个地方,this.$data.myMixinValue和this.myMixinValue,这样正常吗?
- nginx - ASP.NET Core + Redis + nginx 的会话 id 总是在变化
- sql - DB2 中的查询问题——无法找到原因
- c# - 使用 selenium 和 c# 添加到集合时如何过滤元素
- c++ - 尝试旋转空文件时提升日志rotate_file引发错误?
- java - 如何使用 Java 8 流组合逻辑以根据列表大小条件添加到列表中
- delphi - 无法使用 Delphi TWebBrowser 加载站点
- excel - 工作表中的命名范围计数在具有命名范围时结果为零
- foreign-keys - 我的 CRUD 应用程序应该对数据执行验证还是应该是数据库操作?
- javascript - 如何在 Visual Studio 中导入 JavaScript 库?