【问题标题】:scraping from each table based on dates根据日期从每个表中抓取
【发布时间】:2020-10-01 09:29:27
【问题描述】:

我正在尝试从 1995 年至今抓取数据 https://www.bps.go.id/indicator/3/1/25/inflasi-umum-.html,有什么办法可以做到吗?我被困住了,因为每年都有特定的表格和不同的 html。先感谢您

【问题讨论】:

  • lxmlbeautifulsoup 库可能很有用。
  • 我可以做一次吗?或者我必须刮掉每个 html bcs 每个日期都有不同的 html
  • 我认为每页一次就足够了。

标签: python-3.x pandas web-scraping


【解决方案1】:

首先,从select标签中提取options值,得到每年的url:

import requests
from bs4 import BeautifulSoup
import pandas as pd

baseUrl = "https://www.bps.go.id"
dateFrom = 1995
dateTo = 2019

#get the options 
r = requests.get(f"{baseUrl}/indicator/3/1/25/inflasi-umum-.html")
soup = BeautifulSoup(r.text, "html.parser")
years = dict([
    (t.text, t["value"]) 
    for t in soup.find("select").findAll("option") 
    if t.get("value")
])

然后遍历您每年的范围,并使用pandas 提取表,这样您就有一个字典,其中键为年份,Dataframe 为值:

#iterate through years
data = {}
ranges = range(dateFrom, dateTo + 1)
for n in ranges:
  print(f"get data for year {n}")
  r = requests.get(f"{baseUrl}{years[str(n)]}")
  table = pd.read_html(r.text)
  data[str(n)] = table[2]

print(data)

Try this on repl.it

【讨论】:

  • 非常感谢!我可以问一下,为什么年份必须是dict?我可以换成别的吗?
  • 在代码中 bave years 就像{ "2019": "/......." } 这样您可以在循环中使用 years["2019"] 直接获取路径值,但您也可以根据需要创建一个数组跨度>
  • 好的,谢谢!还有一个问题,您是否有删除第一个输出的想法,因为我想将其转换为 csv 。抱歉打扰您 =>[ 0 1 0 DATA SENSUS NaN,0 1 2 3 0 NaN Facebook NaN Instagram 1 NaN Twitter NaN Youtube
  • 我已经用 table[2] 更新了上面的代码,只得到没有表头的表
  • this
猜你喜欢
  • 2021-03-06
  • 2014-08-03
  • 2021-07-07
  • 2013-03-02
  • 2012-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多