如果你使用 BeautifulSoup 来获取 <script> 标签的内容,json module 可以用一点字符串魔法来完成剩下的工作:
jsonValue = '{%s}' % (textValue.partition('{')[2].rpartition('}')[0],)
value = json.loads(jsonValue)
上面的 .partition() 和 .rpartition() 组合将 JavaScript 文本块中第一个 { 和最后一个 } 上的文本分开,这应该是您的对象定义。通过将大括号添加回文本,我们可以将其提供给 json.loads() 并从中获取 python 结构。
这是因为 JSON 基本上是 Javascript 文字语法对象、数组、数字、布尔值和空值。
演示:
>>> import json
>>> text = '''
... var page_data = {
... "default_sku" : "SKU12345",
... "get_together" : {
... "imageLargeURL" : "http://null.null/pictures/large.jpg",
... "URL" : "http://null.null/index.tmpl",
... "name" : "Paints",
... "description" : "Here is a description and it works pretty well",
... "canFavorite" : 1,
... "id" : 1234,
... "type" : 2,
... "category" : "faded",
... "imageThumbnailURL" : "http://null.null/small9.jpg"
... }
... };
... '''
>>> json_text = '{%s}' % (text.partition('{')[2].rpartition('}')[0],)
>>> value = json.loads(json_text)
>>> value
{'default_sku': 'SKU12345', 'get_together': {'imageLargeURL': 'http://null.null/pictures/large.jpg', 'URL': 'http://null.null/index.tmpl', 'name': 'Paints', 'description': 'Here is a description and it works pretty well', 'canFavorite': 1, 'id': 1234, 'type': 2, 'category': 'faded', 'imageThumbnailURL': 'http://null.null/small9.jpg'}}
>>> import pprint
>>> pprint.pprint(value)
{'default_sku': 'SKU12345',
'get_together': {'URL': 'http://null.null/index.tmpl',
'canFavorite': 1,
'category': 'faded',
'description': 'Here is a description and it works pretty '
'well',
'id': 1234,
'imageLargeURL': 'http://null.null/pictures/large.jpg',
'imageThumbnailURL': 'http://null.null/small9.jpg',
'name': 'Paints',
'type': 2}}