使用python从javascript标记中解析可变数据

问题描述 投票:11回答:1

我正在使用BeautifulSoup和Requests抓取一些网站。我正在检查一个页面,其数据位于<script language="JavaScript" type="text/javascript">标记内。它看起来像这样:

<script language="JavaScript" type="text/javascript">
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"
       ......

有没有办法可以在这个脚本标签中的page_data变量中创建一个python字典或json对象?那会比使用BeautifulSoup获得价值更好。

python html json beautifulsoup python-requests
1个回答
22
投票

如果你使用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}}
© www.soinside.com 2019 - 2024. All rights reserved.