【发布时间】:2020-12-21 13:56:40
【问题描述】:
我正在尝试从有点非结构化的 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 表格 ** Here is the link "Table - Techniques Used"
【问题讨论】:
-
您能提供您的表格结构作为文本吗?为了更好的可读性
-
是的,先生 - 这会很棒。如果您提供这些数据,那么我们将能够为您提供帮助。
-
这里是链接,attack.mitre.org/groups/G0004 要使用的表是“使用的技术”
-
并把它剪下来。 5 行 w 样本奇怪的结构比扔 20 行并让我们整理要好。
标签: python beautifulsoup html-tableextract