使用python从html文档中提取javascript变量值

Sha*_*haf 2 javascript python json

我需要使用json对象解析包含javascript代码的HTML文档.

像这样的东西:

<html>
   <head>
   </head>
<body>
    <script type="text/javascript">
        myJSONObject = {"name": "steve", "city": "new york"}
    </script>

   <p>Hello World.</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

如何用python提取myJSONObject值?

phi*_*hag 6

您可以使用lxml来解析HTML,然后提取JSON:

>>> import lxml.etree,json
>>> s = '''<html><body><script type="text/javascript">
             myJSONObject = {"name": "steve", "city": "new york"}
           </script></body></html>'''
>>> js = lxml.etree.HTML(s).find('.//body/script').text
>>> jsonCode = js.partition('=')[2].strip()
>>> json.loads(jsonCode)
{u'city': u'new york', u'name': u'steve'}
Run Code Online (Sandbox Code Playgroud)