【发布时间】:2017-02-13 08:34:27
【问题描述】:
编辑:
所以我已将下面的脚本代码保存到一个文本文件中,但使用 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]
【问题讨论】:
-
我相信你可以使用 selenium 来做类似的事情,例如:stackoverflow.com/questions/10455130/…
-
是的,我正在使用 selenium 来解析 html 内容。我的代码是: [code] req=urllib2.Request(productions_url, headers={'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:27.0) Gecko/20100101 Firefox/27.0'}) p=urllib2 .urlopen(req) 汤=BeautifulSoup(p.readlines()[0], 'html.parser')[/code]。我的问题是,一旦我解析了 html,如何提取这两条特定的行。
-
HTML 解析器不会帮助你,因为那是 JavaScript。所以,你必须自己解析它。
标签: python graph screen-scraping