2012-11-08 5 views
10

BeautifulSoup 및 Requests를 사용하여 일부 웹 사이트를 긁고 있습니다. 내가 검사하고있는 한 페이지에 <script language="JavaScript" type="text/javascript"> 태그 내부에 데이터가 있습니다. 그것은 다음과 같습니다Python을 사용하여 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 변수 중 파이썬 사전 또는 JSON 객체를 생성 할 수있는 방법이 있나요? 그러면 BeautifulSoup로 값을 얻으려고 훨씬 더 좋을 것입니다. 당신이 <script> 태그의 내용을 얻을 수 BeautifulSoup로를 사용하는 경우

답변

22

json module 문자열 마법의 비트와 함께 나머지 작업을 수행 할 수 있습니다

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

.split().rsplit() 콤보는 위의 첫 번째 {에 텍스트를 분할 마지막으로 }의 자바 스크립트 텍스트 블록에서 개체 정의 여야합니다. 텍스트에 중괄호를 다시 추가하여 json.loads()에 피드를 제공하고 파이썬 구조를 가져올 수 있습니다.

데모 :

>>> 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}} 
+0

이 정말 좋은이며 의미가 있습니다. 이걸 도와 줘서 고마워. – ajt

+0

개체의 키를 나타내는 데 따옴표를 사용하지 않는 개체 선언에 대해 용도 변경을 어떻게 할 수 있는지 알고 싶습니다. 'default_sku : "SKU12345", ...'. 그것은 아마도 단지 정규식을 취할 것입니다 ... – 2rs2ts

+0

@ 2rs2ts : 인용문을 추가하는 이전 답변은 [아름다운 수프를 사용하여 데이터를 스크랩하는 동안 html 태그 문제] (http://stackoverflow.com/a/14122300)를 참조하십시오. 유효한 JSON을 만드십시오. –