簡體   English   中英

在 Python 中使用 BeautifulSoup 從 HTML Script 標簽中提取 JSON

[英]Extract JSON from HTML Script tag with BeautifulSoup in Python

我有以下 HTML,我應該怎么做才能從變量中提取 JSON: window.__INITIAL_STATE__

<!DOCTYPE doctype html>

<html lang="en">
<script>
                  window.sessConf = "-2912474957111138742";
                  /* <sl:translate_json> */
                  window.__INITIAL_STATE__ = { /* Target JSON here with 12 million characters */};
                  /* </sl:translate_json> */
                </script>
</html>

您可以使用以下 Python 代碼來提取 JavaScript 代碼。

soup = BeautifulSoup(html)
s=soup.find('script')
js = 'window = {};\n'+s.text.strip()+';\nprocess.stdout.write(JSON.stringify(window.__INITIAL_STATE__));'
with open('temp.js','w') as f:
    f.write(js)

JS 代碼將寫入文件“temp.js”。 然后就可以調用node執行JS文件了。

from subprocess import check_output
window_init_state = check_output(['node','temp.js'])

python 變量window_init_state包含 JS 對象window.__INITIAL_STATE__的 JSON 字符串,您可以在 python 中使用JSONDecoder進行解析。

例子

from subprocess import check_output
import json, bs4
html='''<!DOCTYPE doctype html>

<html lang="en">
<script> window.sessConf = "-2912474957111138742";
                  /* <sl:translate_json> */
                  window.__INITIAL_STATE__ = { 'Hello':'World'};
                  /* </sl:translate_json> */
                </script>
</html>'''
soup = bs4.BeautifulSoup(html)
with open('temp.js','w') as f:
    f.write('window = {};\n'+
            soup.find('script').text.strip()+
            ';\nprocess.stdout.write(JSON.stringify(window.__INITIAL_STATE__));')
window_init_state = check_output(['node','temp.js'])
print(json.loads(window_init_state))

輸出:

{'Hello': 'World'}

gdlmx 的代碼是正確的,非常有幫助。

from subprocess import check_output
soup = BeautifulSoup(html)
s=soup.find('script')
js = 'window = {};\n'+s.text.strip()+';\nprocess.stdout.write(JSON.stringify(window.__INITIAL_STATE__));'
window_init_state = check_output(['node','temp.js'])

type(window_init_state) 將是 . 那么你應該使用以下代碼。

jsonData= window_init_state.decode("utf-8")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM