首页 > 解决方案 > 如何使用 python 从交互式图表中抓取数据?

问题描述

我有一个下一个链接,它代表我想要抓取的精确图表:https ://index.minfin.com.ua/ua/economy/index/svg.php?indType=1&fromYear=2010&acc=1

我简直无法理解它是 xml 还是 svg 图以及如何抓取数据。我想我需要使用 bs4,请求但不知道该怎么做。

任何人都可以帮忙吗?

标签: pythonweb-scrapingbeautifulsouppython-requests

解决方案


您将像这样加载 HTML:

import requests

url = "https://index.minfin.com.ua/ua/economy/index/svg.php?indType=1&fromYear=2010&acc=1"
resp = requests.get(url)
data = resp.text

然后,您将使用此 HTML 创建一个 BeatifulSoup 对象。

from bs4 import BeautifulSoup

soup = BeautifulSoup(html, features="html.parser")

在此之后,如何解析出你想要的东西通常是非常主观的。候选代码可能会有很大差异。我是这样做的:

使用 BeautifulSoup,我解析了所有“矩形”并检查该矩形中是否存在“onmouseover”。

rects = soup.svg.find_all("rect")
yx_points = []
for rect in rects:
    if rect.has_attr("onmouseover"):
        text = rect["onmouseover"]
        x_start_index = text.index("'") + 1
        y_finish_index = text[x_start_index:].index("'") + x_start_index
        yx = text[x_start_index:y_finish_index].split()
        print(text[x_start_index:y_finish_index])
        yx_points.append(yx)

从下图中可以看出,我刮掉onmouseover=了一部分并得到了这些02.2015 155,1部分。

在这里,这就是yx_points现在的样子:

[['12.2009', '100,0'], ['01.2010', '101,8'], ['02.2010', '103,7'], ...]

在此处输入图像描述


推荐阅读