如何使用python从网站上抓取图表?

Ilu*_*ics 1 python screen-scraping graph

编辑:

因此,我已将下面的脚本代码保存到文本文件中,但使用 re 提取数据仍然没有返回任何内容。我的代码是:

file_object = open('source_test_script.txt', mode="r")
soup = BeautifulSoup(file_object, "html.parser")
pattern = re.compile(r"^var (chart[0-9]+) = new Highcharts.Chart\(({.*?})\);$", re.MULTILINE | re.DOTALL)
scripts = soup.find("script", text=pattern)
profile_text = pattern.search(scripts.text).group(1)
profile = json.loads(profile_text)

print profile["data"], profile["categories"]
Run Code Online (Sandbox Code Playgroud)

我想从网站中提取图表数据。以下是图表的源代码。

  <script type="text/javascript">
    jQuery(function() {

    var chart1 = new Highcharts.Chart({

          chart: {
             renderTo: 'chart1',
              defaultSeriesType: 'column',
            borderWidth: 2
          },
          title: {
             text: 'Productions'
          },
          legend: {
            enabled: false
          },
          xAxis: [{
             categories: [1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016],

          }],
          yAxis: {
             min: 0,
             title: {
             text: 'Productions'
          }
          },

          series: [{
               name: 'Productions',
               data: [1,1,0,1,6,4,9,15,15,19,24,18,53,42,54,53,61,36]
               }]
       });
    });

    </script>
Run Code Online (Sandbox Code Playgroud)

网站上有几个类似的图表,称为“chart1”、“chart2”等。我想提取以下数据:每个图表的类别线和数据线:

categories: [1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014,2015,2016]

data: [1,1,0,1,6,4,9,15,15,19,24,18,53,42,54,53,61,36]
Run Code Online (Sandbox Code Playgroud)

And*_*ahl 7

另一种方法是像在控制台中一样使用 Highcharts 的 JavaScript 库,并使用 Selenium 提取它。

import time
from selenium import webdriver

website = ""

driver = webdriver.Firefox()
driver.get(website)
time.sleep(5)

temp = driver.execute_script('return window.Highcharts.charts[0]'
                             '.series[0].options.data')
data = [item[1] for item in temp]
print(data)
Run Code Online (Sandbox Code Playgroud)

根据您尝试提取案例的图表和系列,可能会略有不同。