python解析java文件_使用python从javascript标签中解析变量数据

本文介绍了如何使用Python的BeautifulSoup库配合json模块,从JavaScript标签中的文本块中解析出JSON格式的数据。通过特定的字符串分割方法,提取出JSON对象,并用json.loads()转换为Python结构。示例中展示了如何解析包含商品信息的JavaScript变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果您使用BeautifulSoup获取< script>的内容.标签,

json module可以做一些字符串魔术的休息:

jsonValue = '{%s}' % (textValue.split('{', 1)[1].rsplit('}', 1)[0],)

value = json.loads(jsonValue)

上面的.split()和.rsplit()组合分割了JavaScript文本块中的第一个{和最后一个}上的文本,该文本块应该是您的对象定义.通过将括号添加到文本中,我们可以将其添加到json.loads()并从中获取一个python结构.

示范:

>>> import json

>>> textValue = '''

... 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"

... }

... };

... '''

>>> jsonValue = '{%s}' % (textValue.split('{', 1)[1].rsplit('}', 1)[0],)

>>> value = json.loads(jsonValue)

>>> value

{u'default_sku': u'SKU12345', u'get_together': {u'category': u'faded', u'canFavorite': 1, u'name': u'Paints', u'URL': u'http://null.null/index.tmpl', u'imageThumbnailURL': u'http://null.null/small9.jpg', u'imageLargeURL': u'http://null.null/pictures/large.jpg', u'type': 2, u'id': 1234, u'description': u'Here is a description and it works pretty well'}}

>>> import pprint

>>> pprint.pprint(value)

{u'default_sku': u'SKU12345',

u'get_together': {u'URL': u'http://null.null/index.tmpl',

u'canFavorite': 1,

u'category': u'faded',

u'description': u'Here is a description and it works pretty well',

u'id': 1234,

u'imageLargeURL': u'http://null.null/pictures/large.jpg',

u'imageThumbnailURL': u'http://null.null/small9.jpg',

u'name': u'Paints',

u'type': 2}}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值