【问题标题】:Can't grab tabular content from a webpage using requests无法使用请求从网页中获取表格内容
【发布时间】:2021-08-29 06:41:27
【问题描述】:

我正在尝试从此webpage 中抓取表格内容。要定位内容,需要点击标题How to navigate the interactive report下的12标签。单击该选项卡后,表格内容会显示在该页面底部的Moves To Austin-Round Rock-Georgetown, TX MSA 下。

当我在手动填充数据时观察 chrome 开发工具中的网络活动时,我会注意到一个 post http 请求以及适当的参数被发送到这个 url https://public.tableau.com/vizql/w/CBREMigrationAnalysisv1extract/v/CBREMigrationAnalysis/sessions/F3E2227B603E4F5AB3156667A673CF9E-0:0/commands/tabdoc/set-active-story-point 其中@之间的部分987654326@ 和 /commands/ 是动态的。

但是,我已经能够在发送发布请求之前即时从this url 获取该动态部分。现在,当我尝试使用以下脚本时,我得到500 状态码。

我试过了:

import requests
from bs4 import BeautifulSoup
from pprint import pprint

base = 'https://public.tableau.com/views/CBREMigrationAnalysisv1extract/CBREMigrationAnalysis?:showVizHome=no&:embed=true&parentUrl=https%3A%2F%2Fwww.cbre.us%2Fresearch-and-reports%2FCOVID-19-Impact-on-Resident-Migration-Patterns'
link = 'https://public.tableau.com/vizql/w/CBREMigrationAnalysisv1extract/v/CBREMigrationAnalysis/sessions/{}/commands/tabdoc/set-active-story-point'

payload = {
    'storyboard': 'CBRE Migration Analysis',
    'storyPointId': '14',
    'shouldAutoCapture': 'false',
    'shouldAutoRevert': 'true'
}

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36',
    'x-requested-with': 'XMLHttpRequest',
    'x-newrelic-id': 'XA4CV19WGwIBV1RVBQQBUA==',
    'x-tsi-active-tab': 'CBRE%20Migration%20Analysis',
    'x-tsi-supports-accepted': 'true',
    'referer': base,
}
with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36'
    r = s.get(base)
    post_link = link.format(r.headers['X-Session-Id'])
    s.headers.update(headers)
    res = s.post(post_link,data=payload)
    print(res.status_code)
    pprint(res.json()['vqlCmdResponse']['layoutStatus']['applicationPresModel'])

如何使用请求从该页面访问表格内容?

【问题讨论】:

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


    【解决方案1】:

    我刚刚在this Tableau Scraper library 中实现了故事点功能。结帐the storypoint section

    以下代码将显示所有故事点,并转到 ID 为 14 的故事点(相当于 UI 中标题为 12 的故事点)。然后它将名称为 P2P Table 的工作表放入 pandas 数据框:

    from tableauscraper import TableauScraper as TS
    
    url = 'https://public.tableau.com/views/CBREMigrationAnalysisv1extract/CBREMigrationAnalysis'
    ts = TS()
    ts.loads(url)
    wb = ts.getWorkbook()
    
    print(wb.getStoryPoints())
    print("go to specific storypoint")
    sp = wb.goToStoryPoint(storyPointId=14)
    
    print(sp.getWorksheetNames())
    print(sp.getWorksheet("P2P Table").data)
    

    Try this on repl.it

    【讨论】:

      猜你喜欢
      • 2020-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多