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

ajt*_*ajt 12 html python json beautifulsoup python-requests

我正在使用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"
       ......
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*ers 23

如果你使用BeautifulSoup来获取<script>标签的内容,那么json模块可以通过一些字符串魔术完成剩下的工作:

 jsonValue = '{%s}' % (textValue.partition('{')[2].rpartition('}')[0],)
 value = json.loads(jsonValue)
Run Code Online (Sandbox Code Playgroud)

.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}}
Run Code Online (Sandbox Code Playgroud)