BeautifulSoup & HTML 新手,我以前从未见过这种类型的页面。我正在尝试从威斯康星州戴恩县 2008 年总统竞选中提取数据。
链接:https://www.countyofdane.com/clerk/elect2008d.html
总统竞选的数据似乎是在硬编码表中?它不存储在 HTML 标记或我之前遇到过的任何内容之间。
我可以通过迭代 < !-- #-->
来提取数据吗?不知何故?我是否应该将页面保存为 HTML 文件并在表格周围添加正文标记,以便更容易解析?
最佳答案
这个问题实际上涉及到文本解析,因为表格位于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'],
...
],
...
]
当然,这不包括表名称和对角线标题,这可能很难获得,但并非不可能。另外,您可能希望将表的总行与其他数据行分开。无论如何,我认为这对您来说是一个很好的开始示例。
关于python - 这个怎么解析呢?尝试使用 BeautifulSoup 和 Python 从非 HTML 网页提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41172436/