2011-10-14 72 views
0

我需要使用json對象解析包含javascript代碼的HTML文檔。從python的html文檔中提取javascript變量值

事情是這樣的:

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

    <p>Hello World.</p> 
</body> 
</html> 

我怎樣才能提取與蟒蛇myJSONObject價值?

+0

你能提取出你的.js先向? –

+0

不,我只有html文件和裏面的JavaScript代碼。 – Shahaf

回答

4

您可以使用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'}