我什至不知道这是否可行,但我希望有一种方法可以通过 Python 自动收集保存在 JavaScript 对象中的数据。例如,我正在尝试从 http://cryptocurrencychart.com/top/10 访问图表数据.
我认为最简单的方法是通过 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 之类的东西以编程方式完成,以便我可以自动化它以供将来获取数据。
最佳答案
您可以使用 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 个元素。
关于javascript - 如何通过 Python 以编程方式访问网站中的 JavaScript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45493716/