如何解析这个?尝试使用BeautifulGroup和Python从非HTML网页中提取数据

2024-09-30 01:26:49 发布

您现在位置:Python中文网/ 问答频道 /正文

beauthulsoup&HTML新手,我以前从未见过这种类型的页面。我试图从2008年威斯康星州丹恩县的总统竞选中获取数据。在

链接:https://www.countyofdane.com/clerk/elect2008d.html

总统竞选的数据在一个硬编码的表格里?它不会存储在HTML标记之间,或者我以前遇到过的任何东西。在

我可以通过迭代< !-- #-->来获取数据吗?我是否应该将页面另存为HTML文件,并在表周围添加body标记以便更容易解析?在


Tags: https标记com类型链接htmlwww页面
1条回答
网友
1楼 · 发布于 2024-09-30 01:26:49

这个问题实际上发生在文本解析中,因为表位于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)

这将打印一个列表列表-每个表都有数据行的子列表:

^{pr2}$

当然,这不包括表名和对角线标题,这可能很难获得,但并非不可能。另外,您可能需要将表中的合计行与其他数据行分开。无论如何,我认为这对你来说是一个很好的开始。在

相关问题 更多 >

    热门问题