繁体   English   中英

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

[英]How to parse this? Trying to pull data from non-HTML webpage using BeautifulSoup and Python

这里是BeautifulSoup和HTML的新手,我以前从未见过这种类型的页面。 我正在尝试从2008年在威斯康星州丹恩县举行的总统大选中获取数据。

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

总统竞选的数据似乎在硬编码表中? 它不会存储在HTML标记之间,也不会存储在我之前遇到的任何东西之间。

我可以通过以某种方式遍历< !-- #-->来提取数据吗? 我是否应该将页面另存为HTML文件,并在表格周围添加body标记,以便更易于解析?

由于表是在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'],
        ...
    ],
    ...
]

当然,这不包括表名和对角标头,这些名称可能很难获得,但并非不可能。 另外,您可能希望将总行与表的其他数据行分开。 无论如何,我认为这可能是一个很好的入门示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM