【问题标题】:How to fetch Parent and child items completely, Python 3.6如何完全获取父项和子项,Python 3.6
【发布时间】:2019-12-10 16:07:22
【问题描述】:

The way I am able to fetch all the details, can I even be able to fetch the sub datasets name which are present in the providers dataset? I wish to have providers name followed by dataset name and further followed by datasets present in itThe below image link gives the hierarchy of one provider, similarly we have many providers, can I fetch all the details using API for all the providers?This is the output .csv which I am able to fetch the details after running the code.The below image gives the details about one provider named "AMECO" in which I am unable to fetch the Datasets title and child datasets, in turn able to fetch sub-child items.下面的代码工作效率很高,但for循环的少数部分没有获取正确的 信息。有人可以帮帮我吗。我想获取所有存在于It is the link which provides the information about the Proviers提供者列表中的数据集。反过来;主要数据集标题我无法进入 csv 文件。

import requests, os, sys, csv
import pandas as pd list
from bs4 import BeautifulSoup

pd.set_option('display.max_colwidth', 10000)
pd.set_option('display.expand_frame_repr', False)

以下是提供有关提供商信息的链接。

URL_1 = 'https://db.nomics.world/providers'
URL_2 = 'https://db.nomics.world/'

Required_Columns = ['Provider', 'Region', 'Website', 'In DBnomics since', 'Updated by DBnomics on', 'Dataset Name', 'Link']

print('\n> Retrieve DBNomics Providers')

DBN_Providers = []

Response = requests.get(URL_1)
Soup = BeautifulSoup(Response.content, 'html.parser')
for Class_L1 in Soup.findAll('div', {'class': 'my-8 sm:flex sm:flex-wrap sm:-mx-4'}):
    for Class_L2 in Class_L1.findAll('h2', {'class' : 'mb-2 font-bold text-grey-darkest text-xl group-hover:underline'}):
Provide_Code = Class_L2.text
Provide_Code = Provide_Code.strip()
DBN_Providers.append(Provide_Code)
print('\n>> Total Providers:', len(DBN_Providers))
Details_All = pd.DataFrame()
for I, Provider in enumerate(DBN_Providers, start=1):
URL = URL_2 + Provide
print('%s > %s : %s'%(I, Provider, URL))
Meta_Data = {}
Meta_Data['Provider'] = Provider
Response = requests.get(URL)
Soup = BeautifulSoup(Response.content, 'html.parser')
# Meta Data
for Class_L1 in Soup.findAll('dl', {'class': 'dl-properties'}):
TList = []
for Item in Class_L1.findAll('dd'):
Item = Item.text
Item = Item.strip()
TList.append(Item)
Meta_Data['Region']  = TList[0]
Meta_Data['Website']  = TList[1]
Meta_Data['In DBnomics since']  = TList[2]
Meta_Data['Updated by DBnomics on'] = TList[3]
Meta_Data = pd.DataFrame([Meta_Data])
# Dataset Details
Dataset_List = []
for Class_L1 in Soup.findAll('div', {'id': 'category-tree'}):
for Class_L2 in Class_L1.findAll('ul', {'class': 'list-reset mb-6'}):
for Class_L3 in Class_L2.findAll('details', {'class': 'my-4'}):
for Class_L4 in Class_L3.findAll('a', {'class': 'mr-1'}):
TList = []
Dataset_Name = Class_L4.text
Dataset_Name = Dataset_Name.strip()
TList.append(Dataset_Name)
HREF = Class_L4.get('href')
TList.append(URL_2 + HREF.strip())
Dataset_List.append(TList)
Dataset_DF = pd.DataFrame(Dataset_List, columns=['Dataset Name', 'Link'])
DF = pd.concat([Meta_Data, Dataset_DF], sort=False)
DF = DF.sort_values(['Provider'], ascending=[True])
DF = DF.fillna(method='ffill')
DF = DF.dropna(subset=['Dataset Name'])
Details_All = Details_All.append(DF, sort=False)

Details_All = Details_All.drop_duplicates()
Details_All = Details_All[Required_Columns]
Details_All.to_csv('Details_All.csv', index = False, encoding='utf-8-sig')

【问题讨论】:

  • 使用API让您的生活更轻松API LINK

标签: python pandas beautifulsoup


【解决方案1】:

使用API 并抓取您需要的任何内容:

import requests
import csv

r = requests.get('https://api.db.nomics.world/v22/providers/').json()

data = []
for item in r['providers']['docs']:
    item = (item['code'], item['region'],
            item['website'], item['converted_at'][0:10], item['name'], f"https://db.nomics.world/{item['code']}")
    data.append(item)


with open('output.csv', 'w+', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['Name', 'Region', 'Website',
                     'Updated by DBnomics on', 'Dataset Name', 'Link'])
    writer.writerows(data)
    print("Operation Completed")

在线查看输出:click here

您还可以通过以下提供者名称循环数据:

https://api.db.nomics.world/v22/providers/AMECO

类似:

import requests

r = requests.get('https://api.db.nomics.world/v22/providers/AMECO').json()

for item in r['category_tree'][0:]:
    pop = [oka['name'] for oka in item['children'][0:]]
    print(pop)

输出:

['Population', 'Labour force statistics', 'Unemployment', 'Employment, persons (national accounts)', 'Employment, full-time equivalents (national accounts)', 'Self-employed, persons (national accounts)', 'Wage and salary earners, persons (national accounts)', 'Wage and salary earners, full-time equivalents (national accounts)']
['Private final consumption expenditure', 'Private final consumption expenditure per head of population', 'Actual individual final consumption of households', 'Consumer price index', 'Total final consumption expenditure of general government', 'Collective consumption expenditure of general government', 'Individual consumption expenditure of general government', 'Total consumption']
['Gross fixed capital formation, total economy and sectors', 'Gross fixed capital formation at current prices, sectors', 'Net fixed capital formation, total economy', 'Net fixed capital formation at current prices, sectors', 'Consumption of fixed capital, total economy', 'Consumption of fixed capital, general government', 'Gross fixed capital formation by type of goods at current prices', 'Gross fixed capital formation by type of goods at constant prices', 'Gross fixed capital formation by type of goods, price deflators', 'Change in inventories and net acquisition of valuables', 'Gross capital formation', 'Gross saving', 'Net saving']
['Domestic demand excluding change in inventories', 'Domestic demand including change in inventories', 'Final demand', 'Contributions to the change of the final demand deflator']
['Gross national income', 'Gross national income per head of population', 'Net national income', 'National disposable income at current prices', 'Gross national disposable income per head of population']
['Gross domestic product', 'Gross domestic product per head of population', 'Gross domestic product per person employed', 'Gross domestic product per hour worked', 'Potential gross domestic product at constant prices', 'Trend gross domestic product at constant prices', 'GDP at constant prices adjusted for the impact of terms of trade per head', 'Contributions to the change of GDP at constant market prices', 'Alternative definitions domestic product at current prices', 'Gross value added, total economy']
['Compensation of employees', 'Taxes linked to imports and production and subsidies, total economy', 'Operating surplus, total economy', 'Nominal compensation per employee, total economy', 'Real compensation per employee, total economy', 'Adjusted wage share', 'Nominal unit labour costs, total economy', 'Real unit labour costs, total economy']
['Net capital stock at constant prices, total economy', 'Factor productivity, total economy', 'Production factors substitution, total economy', 'Marginal efficiency of capital, total economy']
['Exports of goods and services', 'Imports of goods and services', 'Exports of goods', 'Exports of services', 'Imports of goods', 'Imports of services', 'Terms of trade']
['Balances with the rest of the world, national accounts', 'Balances with the rest of the world, BOP statistics']
['Foreign trade at current prices', 'Foreign trade shares in world trade']
['Employment, persons', 'Employment, full-time equivalents', 'Wage and salary earners, persons', 'Wage and salary earners, full-time equivalents', 'Gross value added by main branch at current prices', 'Gross value added by main branch at current prices per person employed', 'Gross value added by main branch at current prices per employee', 'Gross value added by main branch at constant prices', 'Gross value added by main branch at constant prices per person employed', 'Gross value added by main branch at constant prices per employee', 'Price deflator gross value added by main branch', 'Compensation of employees by main branch', 'Nominal compensation by main branch per employee', 'Adjusted wage share by main branch', 'Nominal unit wage costs by main branch', 'Nominal unit labour costs by main branch', 'Real unit labour costs by main branch', 'Industrial production']
['Exchange rates and purchasing power parities', 'Interest rates']
['Revenue', 'Expenditure', 'Balances']
['Revenue', 'Expenditure', 'Balances']
['Revenue (ESA 2010)', 'Expenditure (ESA 2010)', 'Net lending (ESA 2010)', 'Excessive deficit procedure']
['Based on potential GDP (ESA 2010)', 'Based on trend GDP (ESA 2010)']
['Based on ESA 2010', 'Based on ESA 2010 and former definitions (linked series)']

【讨论】:

  • 非常感谢。但是,我可以一次获取完整且唯一的提供商列表吗?由于您曾与一个供应商“AMECO”合作,因此有 62 个供应商。那么,有可能吗?
  • 您可能无法一次全部获得它们,但如果您使用线程,您可以大大增加每次获得的数量,从而大大加快进程@manasakulkarni
  • @maestro.inc 你能帮帮我吗。
猜你喜欢
  • 1970-01-01
  • 2020-04-03
  • 1970-01-01
  • 2016-01-19
  • 2017-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-15
相关资源
最近更新 更多