亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從維基百科獲取和解析數據

從維基百科獲取和解析數據

長風秋雁 2023-08-08 17:31:29
我正在嘗試從維基百科獲取并解析一些數據以進行分析。我正在嘗試提取數據來分析列中因素與幸福分數本身之間的相關性。但該文件未按預期工作。事實上,最終的文件是空的。我嘗試調試,但沒有成功:import requestsimport bs4from bs4 import BeautifulSoupimport csvfrom csv import DictWriterdef get_page(url):    html_file = requests.get(url)    return html_filedef parse_html(html_file):    parsed_html = bs4.BeautifulSoup(html_file.text, 'html.parser')        t = parsed_html.find_all('table')[1]        tr = t.find_all('tr')[0]    headers = []    for header in tr:        for z in header:            if isinstance(z, bs4.element.NavigableString):                header_name = z.strip()                headers.append(header_name)        headers_original = headers    countries = []    prev_rank = ""    for ln, row in enumerate(t.find_all('tr')[2:]):        country = {}        i = 0        col_values = row.find_all('td')                while i < len(headers):            col = col_values[i]            value = col.text.strip()                            if headers[i] in ('Country or region',):                value = str(value)            else:                value = float(value)            country[headers[i]] = value            i += 1        countries.append(country)    return headers, countriesdef write_csv(filename, data, fieldnames):    with open(filename, 'w') as csvfile:        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)        writer.writeheader()        writer.writerows(data)def main():    source = "https://en.wikipedia.org/wiki/World_Happiness_Report"    print(f'Fetching URL {source}...')    page = get_page(source)    print(f'Parsing {source}...')    headers, countries = parse_html(page)    print(f'Writing to a CSV file 1...')    write_csv('worldhappiness.csv', countries, headers)    print(f'Parsing table 3 (simpler table) {source} ...')    headers, countries = parse_html(page)
查看完整描述

1 回答

?
慕絲7291255

TA貢獻1859條經驗 獲得超6個贊

使用 pandas 來實現此目的要簡單得多:

import pandas as pd
tables = pd.read_html('https://en.wikipedia.org/wiki/World_Happiness_Report')
tables[4]

輸出是您的目標表。


查看完整回答
反對 回復 2023-08-08
  • 1 回答
  • 0 關注
  • 171 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號