2014-10-07 30 views
3


我試圖用Python檢索JavaScript變量,我有一些問題...

這裏是可變的樣子:如何使用Python檢索JavaScript變量?

<script type="text/javascript"> 
var exampleVar = [ 
    {...}, 
    {...}, 
    { 
     "key":"0000", 
     "abo": 
      { 
       "param1":"1" 
       "param2":"2" 
       "param3": 
        [ 
         { 
          "param3a1":"000" 
          "param3a2":"111" 
         }, 
         { 
          "param3b1":"100" 
          "param3b2":"101" 
         } 
        ] 
      } 
] 
</script> 

經過一番研究,我發現,它的內容是JSON格式,我是新手...

我現在的問題是,我想檢索「param3b1」(例如)的值在我的Python程序中使用它。
如何在Python中執行此操作?
謝謝!

+0

你可以使用一個模塊,如https://docs.python.org/3/library/json.html?highlight=json#module-json – matsjoyce 2014-10-07 16:25:13

+1

您是否考慮搜索「Python JSON」?看看['json'](https://docs.python.org/2/library/json.html)。 – jonrsharpe 2014-10-07 16:25:46

+0

如果變量在客戶端上,您需要使用ajax或表單發送回來。一旦它在服務器上使用[json編碼器/解碼器](https://docs.python.org/2/library/json.html) – scrappedcola 2014-10-07 16:26:29

回答

1

一步一個腳印,這是你需要做什麼。

  1. 從文件/ html字符串中提取json字符串。您需要首先獲取<script>標記之間的字符串,然後從變量定義
  2. 中提取json字符串中的參數。
從xml.etree進口ElementTree的

import json 
tree = ElementTree.fromstring(js_String).getroot() #get the root 
#use etree.find or whatever to find the text you need in your html file 
script_text = tree.text.strip() 

#extract json string 
#you could use the re module if the string extraction is complex 
json_string = script_text.split('var exampleVar =')[1] 
#note that this will work only for the example you have given. 
try: 
    data = json.loads(json_string) 
except ValueError: 
    print "invalid json", json_string 
else: 
    value = data['abo']['param3']['param3b1'] 
+0

嗨,謝謝你這個很好的答案。你有一個關於如何使用重新模塊的好鏈接,因爲我試圖低估它,但我不能......謝謝! – Sek8 2014-10-07 17:34:26

+0

@ Sek8在理解re模塊之前,您需要了解regex。 http://en.wikipedia.org/wiki/Regular_expression。但是,如果您正在解析的文本足夠簡單,那麼您應該能夠使用split()提取JSON對象, – tom 2014-10-07 17:38:41

2

您需要使用JSON模塊。

import json 

myJson = json.loads(your_json_string) 

param3b1 = myJson['abo']['param3'][1]['param3b1'] 

JSON模塊文檔:https://docs.python.org/2/library/json.html

+1

非常感謝!我現在的問題是如何從整個'

  • 11. 從Javascript文件中檢索變量
  • 12. JavaScript GET來檢索一個變量
  • 13. 在Javascript中使用PHP檢索的變量
  • 14. Wicket檢索JavaScript變量在java中使用
  • 15. 函數使用JavaScript和Jquery檢索url變量?
  • 16. 用jquery檢索變量ajax
  • 17. 用消息檢索變量
  • 18. 如何使用javascript檢索localStorage數據
  • 19. 如何使用javascript檢索codeigniter的cookie?
  • 20. 如何從Python遠程系統中檢索環境變量?
  • 21. 如何檢索Django/W cookie中的cookie來設置Python變量
  • 22. 如何存儲和檢索我所做的JavaScript變量?
  • 23. 如何將javascript標籤的圖像檢索到變量中?
  • 24. 如何從javascript變量檢索json數據
  • 25. 如何創建會話變量,並在JavaScript中檢索MVC3
  • 26. 如何從JavaScript函數中檢索Java變量?
  • 27. Python與特使,如何使用變量
  • 28. 使用javascript檢查變量中的值
  • 29. 如何從cfquery中檢索SQL變量?
  • 30. 如何在行動檢索$ _ POST變量