我正在使用 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 获取值要好得多。
最佳答案
如果您使用 BeautifulSoup 获取 <script>
的内容标记, json
module可以用一些字符串魔术来完成剩下的工作:
jsonValue = '{%s}' % (textValue.partition('{')[2].rpartition('}')[0],)
value = json.loads(jsonValue)
.partition()
和 .rpartition()
上面的组合在第一个 {
上拆分文本最后一个 }
在 JavaScript 文本 block 中,这应该是您的对象定义。通过将大括号添加回文本,我们可以将其提供给 json.loads()
并从中获取 python 结构。
之所以可行,是因为 JSON 基本上是 Javascript 文字语法对象、数组、数字、 bool 值和空值。
演示:
>>> 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}}
关于python - 使用 python 从 javascript 标记中解析变量数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13298201/