這個問題實際上涉及到文本解析因爲臺處於一個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'],
...
],
...
]
這當然不包括表名和對角線頭這可能很難獲得,但並非不可能。另外,您可能希望將總行與表的其他數據行分開。無論如何,我認爲這對你來說可能是一個很好的例子。
您正在解析文本。 BeautifulSoup不會有任何幫助。解析實際數據將會相當簡單,但對角線標題將會......具有挑戰性。 – kindall
一旦你在'
'標籤之間的文本,你可能更好的解析正則表達式。 –@kindall在技術上解析標題並不複雜。首先,你必須測量他們佔據的行數。然後,您可以測量每條線需要預留多少空間。然後每列開始一個字母就是一個名字,列末尾的每個字母都是另一個名字。列用'----'標記。那麼它不是複雜的,只是不是不可能的。 –