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

编辑:

所以我已经将下面的脚本代码保存到一个文本文件中,但是使用 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"]

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

  <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>

网站上有几个类似的图表,分别称为“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]

最佳答案

另一种方法是像在控制台中一样使用 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)

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

https://stackoverflow.com/questions/39864796/

相关文章:

python - 如何清除 PYQTGRAPH 中的 ScatterPlotItem

coldfusion - 如何从 Coldfusion 中的结构数组中删除重复项

sql-server - 为什么即使回滚事务,SQL Server 仍保持可变状态?

c - FreeRTOS 中的抢占

hibernate - Spring Boot/JPA/Hibernate,如何根据Spring配置

php - 使用带有表前缀的 DB::raw()

java - 从测试用例调用 Controller 时,使用自动连线组件测试 Controller

python - Flask 应用程序搜索栏

python - 如何删除 Tkinter OptionMenu 小部件的边框

curl - 如何使用 curl 访问 IBM speech-to-text api?