【问题标题】:How do i webscrape the data in "preview" under "network" using requests?如何使用请求在“网络”下的“预览”中抓取数据?
【发布时间】:2019-07-17 16:38:17
【问题描述】:

例如,在这张图表中: https://www.highcharts.com/stock/demo/basic-line

我正在尝试通过网络抓取此信息

每个下拉列表都有我需要收集以进行分析的信息。目前我正在尝试在 python 中使用 Requests 包但没有太大成功

很想听听任何建议!

【问题讨论】:

  • 到目前为止你有什么?你尝试了什么?
  • 到目前为止,我只有 requests.get(url) 的代码。不幸的是,我是 requests 包的新手,所以我没有尝试过任何真正有用的东西。我知道您通过请求 URL(在“标题”下)转到 highcharts.com/samples/data/aapl-c.json,但是在我正在处理的实际站点上,通过请求 URL 转到链接将导致“405:不允许方法”跨度>
  • 在实际站点上,Request方法是“Post”
  • 那个 json 端点支持 GET 请求,可能是因为您尝试发送 POST 请求而收到 405 错误?

标签: web-scraping python-requests


【解决方案1】:

好的,使用requests.get 发出get 请求,然后使用.json 方法将响应解析为json,然后可选地将时间戳(以毫秒为单位,除以1000 得到秒)转换为datetime 对象,例如这个:

import requests
from datetime import datetime
from pprint import pprint


def get_stock_prices(symbol: str) -> list:
    symbol = symbol.lower()
    url = f'https://www.highcharts.com/samples/data/{symbol}-c.json'
    res = requests.get(url)
    res.raise_for_status()
    prices_raw = res.json()
    return [[datetime.fromtimestamp(t / 1000), price] 
            for t, price in prices_raw]


symbol = 'AAPL'
stocks = get_stock_prices(symbol)
pprint(stocks)

输出:

[[datetime.datetime(2017, 7, 17, 16, 30), 149.56],
 [datetime.datetime(2017, 7, 18, 16, 30), 150.08],
 [datetime.datetime(2017, 7, 19, 16, 30), 151.02],
 [datetime.datetime(2017, 7, 20, 16, 30), 150.34],
 [datetime.datetime(2017, 7, 21, 16, 30), 150.27],
 [datetime.datetime(2017, 7, 24, 16, 30), 152.09],
 [datetime.datetime(2017, 7, 25, 16, 30), 152.74],
 [datetime.datetime(2017, 7, 26, 16, 30), 153.46],

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多