2017-08-03 49 views
0

我甚至不知道這是否可行,但我希望有一種方法可以通過Python自動收集JavaScript對象中保存的數據。舉例來說,我試圖從http://cryptocurrencychart.com/top/10訪問圖表數據。如何以編程方式通過Python訪問網站中的JavaScript變量

我認爲這樣做是通過requests模塊,只是尋找保存數據的SVG元素,如dom.select('.c3-chart-lines .c3-chart-line .c3-shapes-Bitcoin circle'),其中dom是到BeautifulSoup調用生成的對象,然後用最簡單的方法.get('cy')獲取值。但是,如果將cy屬性的值與圖表上的實際值進行比較,則它們不會對齊。

但是,我意識到我可以打開開發者控制檯並通過console.log(CryptoCurrencyChart.chart.data());訪問數據。爲了將這些數據保存到文本文件中,我必須在網頁上創建一個鏈接,以base-64編碼數據作爲href,然後手動單擊該鏈接。

我的問題是,這是否可以通過像Python這樣的程序來完成,這樣我就可以將它自動化以便將來獲取數據。

回答

1

您可以用Selenium來獲得CryptoCurrencyChart.chart.data()對象

#!/usr/bin/env python 

from selenium import webdriver 

link = 'http://cryptocurrencychart.com/top/10' 

class Scraper(object): 
    def __init__(self): 
     options = webdriver.ChromeOptions() 
     options.add_argument('headless') 
     options.binary_location = '/usr/bin/google-chrome-unstable' 
     options.add_argument('window-size=1200x600') 
     self.driver = webdriver.Chrome(chrome_options=options) 

    def scrape(self): 
     self.driver.get(link) 
     result = self.driver.execute_script('return CryptoCurrencyChart.chart.data()') 
     self.driver.quit() 
     return result 

if __name__ == '__main__': 
    scraper = Scraper() 
    scraper.scrape() 

運行self.driver.execute_script('return CryptoCurrencyChart.chart.data()')會給你3個陣列,每個360元。