编辑
我制作了a python library to scrape tableau dashboard。实现更简单:
from tableauscraper import TableauScraper as TS
url = "https://public.tableau.com/views/Colorado_COVID19_Data/CO_Home"
ts = TS()
ts.loads(url)
dashboard = ts.getDashboard()
for t in dashboard.worksheets:
#show worksheet name
print(f"WORKSHEET NAME : {t.name}")
#show dataframe for this worksheet
print(t.data)
run this on repl.it
旧答案
图形似乎是在 JS 中从 API 的结果生成的,如下所示:
POST https://public.tableau.com/TITLE/bootstrapSession/sessions/SESSION_ID
SESSION_ID 参数位于(除其他外)用于构建 iframe 的 URL 中的 tsConfigContainer textarea 中。
从https://covid19.colorado.gov/hospital-data开始:
- 检查类
tableauPlaceholder的元素
- 获取具有
name 属性的param 元素
- 它为您提供网址:
https://public.tableau.com/views/{urlPath}
- 上一个链接为您提供了一个 ID 为
tsConfigContainer 的文本区域,其中包含一堆 json 值
- 提取
session_id和根路径(vizql_root)
- 在
https://public.tableau.com/ROOT_PATH/bootstrapSession/sessions/SESSION_ID 上使用sheetId 作为表单数据进行POST
- 从结果中提取json(结果不是json)
代码:
import requests
from bs4 import BeautifulSoup
import json
import re
r = requests.get("https://covid19.colorado.gov/hospital-data")
soup = BeautifulSoup(r.text, "html.parser")
# get the second tableau link
tableauContainer = soup.findAll("div", { "class": "tableauPlaceholder"})[1]
urlPath = tableauContainer.find("param", { "name": "name"})["value"]
r = requests.get(
f"https://public.tableau.com/views/{urlPath}",
params= {
":showVizHome":"no",
}
)
soup = BeautifulSoup(r.text, "html.parser")
tableauData = json.loads(soup.find("textarea",{"id": "tsConfigContainer"}).text)
dataUrl = f'https://public.tableau.com{tableauData["vizql_root"]}/bootstrapSession/sessions/{tableauData["sessionid"]}'
r = requests.post(dataUrl, data= {
"sheet_id": tableauData["sheetId"],
})
dataReg = re.search('\d+;({.*})\d+;({.*})', r.text, re.MULTILINE)
info = json.loads(dataReg.group(1))
data = json.loads(dataReg.group(2))
print(data["secondaryInfo"]["presModelMap"]["dataDictionary"]["presModelHolder"]["genDataDictionaryPresModel"]["dataSegments"]["0"]["dataColumns"])
从那里你有所有的数据。您将需要寻找数据的拆分方式,因为似乎所有数据都通过单个列表转储。可能查看 JSON 对象中的其他字段会对此很有用。