如何使用python获取脚本中的值

2024-09-30 12:22:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python+靓汤创建一个爬虫。你知道吗

我必须访问标记才能在数据层中获取一些数据。你知道吗

我用beatifulsoup进行了一次搜索,并设法返回了我需要的标记,但我无法将其转换为json来访问信息。你知道吗

这是我用来获取的代码:

    page = get_html('URL')
    dataLayer = page.findAll('script')[NUMBER OF SCRIPT]

这是我的回报:

<script type="text/javascript">
    dataLayer = [{

        'site': {
            'isMobile': false
        },
        'page': {
            'pageType': 'ad_detail',
            'detail': {
                'parent_category_id': '2000',
                'category_id': '2020',
                'state_id': '2',
                'region_id': '31',

                    'ad_id': '293231982',
                    'list_id': '250941507',
                    'city_id': '9208',
                    'zipcode':'34710620',

            },

                'adDetail': {
                    'adID': '293231982',
                    'listID': '250941507',
                    'sellerName': 'Marr',
                    'adDate': '2016-11-30 20:52:11',
                },

        },
        'session': {
            'user': {
                'userID': '',
                'loginType': ''
            }
        },

        'pageType': 'Ad_detail',
        'abtestingEnable' : '1',



        // Listing information

        'listingCategory': '2020',


        // Ad information
        'adId': '293231982',
        'state': '2',
        'region': '31',
        'category': '2020',

         'pictures': '8',
        'listId': '250941507',

        //Account Information

        'loggedUser':'0',

        'referrer': '',

        //User Information


    }];
</script>

我想以adDate和zipcode的形式获取数据。你知道吗


Tags: 数据标记idpagescriptregionadstate
2条回答

您的json使用单引号而不是双引号。 应该将所有单引号替换为双引号,以使数据层变量符合json。你知道吗

一个简单的.replace(“,”)就可以了。你知道吗

注意:还必须用第二个regex删除注释行。你知道吗

s = soup.script.text.replace('\'', '"') # replace ' with "
s = re.search(r'\{.+\}', s, re.DOTALL).group() # get json data
s = re.sub(r'//.+\n', '', s) # replace comment
s = re.sub(r'\s+', '', s) # strip whitspace
s = re.sub(r',}', '}', s) # get rid of last , in the dict
json.loads(s)

输出:

{'abtestingEnable': '1',
 'adId': '293231982',
 'category': '2020',
 'listId': '250941507',
 'listingCategory': '2020',
 'loggedUser': '0',
 'page': {'adDetail': {'adDate': '2016-11-3020:52:11',
   'adID': '293231982',
   'listID': '250941507',
   'sellerName': 'Marr'},
  'detail': {'ad_id': '293231982',
   'category_id': '2020',
   'city_id': '9208',
   'list_id': '250941507',
   'parent_category_id': '2000',
   'region_id': '31',
   'state_id': '2',
   'zipcode': '34710620'},
  'pageType': 'ad_detail'},
 'pageType': 'Ad_detail',
 'pictures': '8',
 'referrer': '',
 'region': '31',
 'session': {'user': {'loginType': '', 'userID': ''}},
 'site': {'isMobile': False},
 'state': '2'}

相关问题 更多 >

    热门问题