【问题标题】:Error scraping Highcharts in Python with selenium使用 selenium 在 Python 中抓取 Highcharts 时出错
【发布时间】:2020-07-10 12:49:37
【问题描述】:

我正在尝试从两个不同的网站上抓取 highcharts, 我在这个 stackoverflow 问题中遇到了这个 execute_script 答案: How to scrape charts from a website with python?

它帮助我从第一个网站上抓取,但是当我在第二个网站上使用它时,它返回以下错误:

line 27, in <module>
    temp = driver.execute_script('return window.Highcharts.charts[0]'

selenium.common.exceptions.JavascriptException: Message: javascript error: Cannot read 
property '0' of undefined

网站是: http://lumierecapital.com/#

您应该单击左侧的性能按钮以获取高图。

目标:我只想从中获取日期和每单位资产净值

和上一个网站一样,这段代码应该打印出一个以 X 和 Y 作为键、日期和数据作为值的字典,但它不适用于这个。

这是python代码:

from bs4 import BeautifulSoup
import requests
from selenium.webdriver.chrome.options import Options
from shutil import which
from selenium import webdriver
import time

chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_path = which("chromedriver")
driver = webdriver.Chrome(executable_path=chrome_path, options=chrome_options)
driver.set_window_size(1366, 768)

driver.get("http://lumierecapital.com/#")

performance_button = driver.find_element_by_xpath("//a[@page='performance']")

performance_button.click()

time.sleep(7)

temp = driver.execute_script('return window.Highcharts.charts[0]'
                            '.series[0].options.data')

for item in temp:
    print(item)


【问题讨论】:

    标签: python selenium web-scraping highcharts


    【解决方案1】:

    您可以使用re模块提取性能图表的值:

    import re
    import requests
    
    
    url = 'http://lumierecapital.com/content_performance.html'
    html_data = requests.get(url).text
    
    for year, month, day, value, datex in re.findall(r"{ x:Date\.UTC\((\d+), (\d+), (\d+)\), y:([\d.]+), datex: '(.*?)' }", html_data):
        print('{:<10} {}'.format(datex, value))
    

    打印:

    30/9/07    576.092
    31/10/07   577.737
    30/11/07   567.998
    31/12/07   556.670
    31/1/08    460.886
    29/2/08    496.740
    31/3/08    484.016
    30/4/08    523.829
    31/5/08    546.661
    30/6/08    494.067
    31/7/08    475.942
    31/8/08    389.147
    30/9/08    299.661
    31/10/08   183.690
    30/11/08   190.054
    31/12/08   211.960
    31/1/09    193.308
    
    ... and so on.
    

    【讨论】:

      猜你喜欢
      • 2022-06-14
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-01
      • 2015-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多