簡體   English   中英

如何使用異常表格從選舉網站上抓取數據

[英]How to scrape data from election website with unusual table

我試圖從選舉網站上抓取一些數據,但不知道如何使用 BeautifulSoup 提取這些數據。

德克薩斯州選舉結果https://results.texas-election.com/contestdetails?officeID=1001&officeName=PRESIDENT%2FVICE-PRESIDENT&officeType=FEDERAL%20OFFICES&from=race

我試過的代碼

import pandas as pd
from bs4 import BeautifulSoup

tx_url = 'https://results.texas-election.com/contestdetails?officeID=1001&officeName=PRESIDENT%2FVICE-PRESIDENT&officeType=FEDERAL%20OFFICES&from=race'


import urllib.request
local_filename, headers = urllib.request.urlretrieve(tx_url)

urllib.error.HTTPError:HTTP 錯誤 403:禁止

soup = BeautifulSoup(tx_url)

/home/server/pi/homes/woodilla/.conda/envs/baseDS_env/lib/python3.7/site-packages/bs4/ init .py:357: UserWarning: "https://results.texas-election.com /contestdetails?officeID=1001&officeName=PRESIDENT%2FVICE-PRESIDENT&officeType=FEDERAL%20OFFICES&from=race" 看起來像一個 URL。 Beautiful Soup 不是 HTTP 客戶端。 您可能應該使用 HTTP 客戶端(如請求)來獲取 URL 后面的文檔,並將該文檔提供給 Beautiful Soup。 那個文件給Beautiful Soup。 % decode_markup

這是表的樣子:

在此處輸入圖片說明

首先,您得到的錯誤意味着您錯誤地使用了BeautifulSoup

您需要像這樣將來自 HTTP 客戶端的響應傳遞給BeautifulSoup

import requests
from bs4 import BeautifulSoup

url = "https://results.texas-election.com/races"

headers = {
    "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36",
}

response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")

其次重要的是,你不需要BeautifulSoup刮該頁面。 一切都以JSON返回。 例如:

import requests

url = "https://results.texas-election.com/static/data/election/44146/246/Federal.json"

headers = {
    "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36",
}
response = requests.get(url, headers=headers).json()

for race in response["Races"]:
    print(f"Results for {race['N']}")
    for candidate in race["Candidates"]:
        print(f"{candidate['N']} - {candidate['P']}: Votes {candidate['V']} - {candidate['PE']}%")
    print(f"Total votes: {race['T']}")
    print("-" * 80)

輸出:

RESIDENT/VICE-PRESIDENT
ROQUE "ROCKY" DE LA FUENTE GUERRA - REP: Votes 7563 - 0.37%
BOB ELY - REP: Votes 3582 - 0.18%
ZOLTAN G. ISTVAN - REP: Votes 1447 - 0.07%
MATTHEW JOHN MATERN - REP: Votes 3512 - 0.17%
DONALD J. TRUMP (I) - REP: Votes 1898664 - 94.13%
JOE WALSH - REP: Votes 14772 - 0.73%
BILL WELD - REP: Votes 15824 - 0.78%
UNCOMMITTED - REP: Votes 71803 - 3.56%
Total votes: 2017167
--------------------------------------------------------------------------------
U. S.  SENATOR
VIRGIL BIERSCHWALE - REP: Votes 20494 - 1.06%
JOHN ANTHONY CASTRO - REP: Votes 86916 - 4.49%
JOHN CORNYN (I) - REP: Votes 1470669 - 76.04%
DWAYNE STOVALL - REP: Votes 231104 - 11.95%
MARK YANCEY - REP: Votes 124864 - 6.46%
Total votes: 1934047
--------------------------------------------------------------------------------
U. S. REPRESENTATIVE DISTRICT 1
JOHNATHAN KYLE DAVIDSON - REP: Votes 9659 - 10.33%
LOUIE GOHMERT (I) - REP: Votes 83887 - 89.67%
Total votes: 93546
--------------------------------------------------------------------------------
and so on ...

編輯:

要獲取您提到的特定URL的數據,只需使用以下命令:

注意:這只是數據的一小部分,因為JSON很大。 我添加了用於轉儲整個JSON代碼,以便您可以按照自己的方式解析它。

import json

import requests

url = "https://results.texas-election.com/static/data/election/44144/108/County.json"

headers = {
    "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36",
}
response = requests.get(url, headers=headers).json()


with open("county_results.json", "w") as output:
    json.dump(response, output, indent=4, sort_keys=True)

for v in response.values():
    for id_, race_data in v["Races"].items():
        print(race_data["C"])

示例輸出:

{'4250': {'id': 4250, 'N': 'KEN WISE (I)', 'P': 'REP', 'V': 0, 'PE': 0.0, 'C': '#E30202', 'O': 1, 'EV': 0}, '6015': {'id': 6015, 'N': 'TAMIKA "TAMI" CRAFT', 'P': 'DEM', 'V': 0, 'PE': 0.0, 'C': '#007BBD', 'O': 2, 'EV': 0}}
{'2966': {'id': 2966, 'N': 'BRENDA MULLINIX (I)', 'P': 'REP', 'V': 0, 'PE': 0.0, 'C': '#E30202', 'O': 1, 'EV': 0}, '6224': {'id': 6224, 'N': 'JANET BUENING HEPPARD', 'P': 'DEM', 'V': 0, 'PE': 0.0, 'C': '#007BBD', 'O': 2, 'EV': 0}}
{'2967': {'id': 2967, 'N': 'MAGGIE JARAMILLO (I)', 'P': 'REP', 'V': 0, 'PE': 0.0, 'C': '#E30202', 'O': 1, 'EV': 0}, '3708': {'id': 3708, 'N': 'TAMEIKA CARTER', 'P': 'DEM', 'V': 0, 'PE': 0.0, 'C': '#007BBD', 'O': 2, 'EV': 0}}
and much, much more...

我是如何找到JSON

我檢查了瀏覽器開發工具的網絡選項卡。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM