gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:19:46 24 4
gpt4 key购买 nike

编辑:

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

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

关于python - 如何使用 python 从网站上抓取图表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39864796/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com