这个问题实际上来自 文本解析,因为表格是 纯文本 在 pre 元素内的。
您可以从这里开始。这个想法是通过使用----- 标题和表格后面的空行来检测表格的开头和结尾。大致如下:
import re
from bs4 import BeautifulSoup
import requests
from ppprint import pprint
url = "https://www.countyofdane.com/clerk/elect2008d.html"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
is_table_row = False
tables = []
for line in soup.pre.get_text().splitlines():
# beginning of the table
if not is_table_row and "-----" in line:
is_table_row = True
table = []
continue
# end of the table
if is_table_row and not line.strip():
is_table_row = False
tables.append(table)
continue
if is_table_row:
table.append(re.split("\s{2,}", line)) # splitting by 2 or more spaces
pprint(tables)
这将打印一个列表列表 - 一个包含每个表的数据行的子列表:
[
[
['0001 T ALBION WDS 1-2', '753', '315', '2', '4', '1', '0', '5', '2', '0', '1'],
['0002 T BERRY WDS 1-2', '478', '276', '0', '0', '0', '0', '2', '0', '0', '1'],
...
['', 'CANDIDATE TOTALS', '205984', '73065', '435', '983', '103', '20', '1491', '316', '31', '511'],
['', 'CANDIDATE PERCENT', '72.80', '25.82', '.15', '.34', '.03', '.52', '.11', '.01', '.18']],
[
['0001 T ALBION WDS 1-2', '726', '323', '0'],
['0002 T BERRY WDS 1-2', '457', '290', '1'],
['0003 T BLACK EARTH', '180', '107', '0'],
...
],
...
]
当然,这不包括表格名称和对角线标题,这可能很难获得,但并非不可能。另外,您可能希望将总行与表的其他数据行分开。无论如何,我认为这对您来说是一个很好的开始示例。