简体   繁体   中英

How do I get the JSON from a script tag of an HTML page?

I have the following text that I parsed from a script tag of an HTML page:



var bnh = {
        bootstrap: {},
        hashedFileNameMap: {"css/main.a.css":"css/main.a-ce49f3c1.css","css/main.css":"css/main-d498c649.css","js/main.a.js":"js/main.a-7daba1f6.js","js/main.js":"js/main-94432af3.js"},
        permalinkUrl: null,
        initialURL: location.href,
        initialModuleID: 'home',
        initialContent: '',
        utils: {},
        queue: {},
        logs: [], // container to store initial logs
        config: {"isWebview":false,"storePickupMinutes":30,"showSeeOther":false,"ryp":"N","preFillCheckbox":true,"isNewSession":true,"featuredCI":"24875","hostname":"https://www.bhphotovideo.com","isTablet":false,"litlePayPageid":"aLGNuLSTJVwgEiCn","seeOther":"https://www.bhphotovideo.com/c/buy/Back-to-School-Savings/ci/22144/N/4019732813/ignore/Y","isCrawler":false,"salesforce_liveagent_content_url":"https://c.la2-c1-ia2.salesforceliveagent.com/content","isEduApproved":false,"timedEvents":{"cartCheckoutMessage":"<strong>Please Note:<\/strong> B&H and our shipping partners are doing our best under difficult circumstances to deliver your order quickly and safely. It is possible that some shipments may experience unforeseen delays. We appreciate your understanding and patience.","freeParkingSuspended":false},"appleSignInClientId":"com.bhphotovideo.signin","cacheDate":"release-WEB-20210407v10-BHJ-DVB27474-22","googlePlusClientId":"1086246549855-s2r4ljelaav8umpv64899d00kvdahg5h.apps.googleusercontent.com","showCurrency":false,"controllerPath":"bnh/controller/","isEmbeddedLiveChatActive":true,"showLiveChat":true,"trackBrowsingHistory":false,"canOrderNowAndPickupToday":false,"activeCurrency":{"code":"USD","description":"US Dollar"},"loadEnsighten":true,"hideShell":false,"isPrivacyProtected":false,"turnto_info":{},"showB2bLogo":false,"tollFreeNumber":"8006066969","bh_mysalesforce_domain":"https://bnh.my.salesforce.com","snapins_button_id":"5732L00000005mQ","websiteClosing":{"isClosed":false,"description":"Shabbat","unformattedEndDate":"2021-04-17 21:00:04.0"},"bi":"","serverName":"DC1230","testEmailAddress":"","locale":"en_US","showCurrencyAsMainPrice":false,"bh_salesforce_domain":"https://bhphotovideo.secure.force.com","holiday":{"showSweepstakesEntry":true,"holidayMode_3":false,"holidayMode_1":false,"holidayMode_7":false,"extendedReturnsEndDate":"12-31-1969 07:00 PM","holidayMode_6":false,"holidayMode_5":false,"holidayMode_4":false,"holidayMode_8":false},"snapins_deployment_name":"Snap_Ins","passwordRequired":true,"snapins_deployment_id":"5721a000000Cfej","urls":{"resetPassword":"https://www.bhphotovideo.com/bnh/controller/home?O=forget&A=resetPassword&Q=reset","wishlist":"https://www.bhphotovideo.com/find/wishlist.jsp","buy":"https://www.bhphotovideo.com/c/buy/","uploadServerUrl":"https://www.bhphotovideo.com/fupload","hoursOfOperation":"https://www.bhphotovideo.com/find/HelpCenter/HoursOfOperation.jsp","ensighten":"//ensighten.bhphoto.com/bhfoto/mobileProd/Bootstrap.js","used":"https://www.bhphotovideo.com/c/browse/Used-Equipment/ci/2870/N/4294247188","eventSpace":"https://www.bhphotovideo.com/find/eventDetails.jsp","cart":"https://www.bhphotovideo.com/find/cart.jsp","assets":"https://www.bhphotovideo.com/FrameWork/mobile/new/","wishlistDetail":"https://www.bhphotovideo.com/find/wishlistDetail.jsp","apertureHost":"https://www.bhphotovideo.com","find":"https://www.bhphotovideo.com/find/","eGiftCard":"https://www.bhphotovideo.com/find/eGiftCard.jsp","synchronyBHBCLogin":"https://www.mysynchrony.com/mysyf/cmp-index.html?market=electronics&store=bhpayboo","litlePath":"eProtect/","secureAPI":"https://www.bhphotovideo.com/bnh/controller/home","api":"https://www.bhphotovideo.com/bnh/controller","sheerid":"https://services.sheerid.com/rest/0.5/","quoteHistoryList":"https://www.bhphotovideo.com/bnh/controller/home?O=myAccount&A=orderHistory&Q=orderHistory&type=quotes","fallback_chat":"https://bhphotovideo.secure.force.com/PrechatBeginPage","contactUs":"https://www.bhphotovideo.com/find/HelpCenter/helpcenter.jsp#contact-us","synchronyBHFCLogin":"https://www.mysynchrony.com/mysyf/cmp-index.html?market=electronics&store=bhphoto","fullSite":"https://www.bhphotovideo.com/bnh/controller/home?O=index.jsp&A=SwitchMobileDesktop&Q=&switchDevice=desktop","techCornerUrl":"https://www.bhphotovideo.com/find/shared/visit-the-tech-corner.jsp","guestCheckout":"https://www.bhphotovideo.com/bnh/controller/home?O=cart&A=checkout&Q=nologin&createNewOrder=true&token=736a1882ab892a8b55d1737eb6038424","orderTimeOut":"https://www.bhphotovideo.com/find/orderTimeOut.jsp","eduAdvantage":"https://www.bhphotovideo.com/find/eduAdvantage.jsp","fullSiteOnce":"https://www.bhphotovideo.com/bnh/controller/home?O=index.jsp&A=SwitchMobileDesktop&Q=&switchDevice=desktop&switchDeviceOnce=true","createAccount":"https://www.bhphotovideo.com/find/createAccount.jsp","imageNotAvailable":"//static.bhphoto.com/images/na.gif","profilePicture":"","writeReview":"https://www.bhphotovideo.com/find/write-review.jsp","bundles":"https://www.bhphotovideo.com/find/bundles.jsp","rewardsLanding":"https://www.bhphotovideo.com/find/RewardsLanding.jsp","browse":"https://www.bhphotovideo.com/c/browse/","aboutUs":"https://www.bhphotovideo.com/find/HelpCenter/AboutUs.jsp","pageNotFound":"https://www.bhphotovideo.com/find/pageNotFound.jsp","friendly_url_controller_name":"c","userAgreement":"https://www.bhphotovideo.com/find/HelpCenter/UserAgreement.jsp","featuredItems":"3929443921+35+38","helpCenter":"https://www.bhphotovideo.com/find/HelpCenter/helpcenter.jsp","eventSpaceList":"https://www.bhphotovideo.com/find/EventSpace.jsp","viewAllDeals":"https://www.bhphotovideo.com/c/buy/rebates-promotions/ci/22144/N/4019732813","dealZone":"https://www.bhphotovideo.com/find/dealZone.jsp","orderHistoryDetail":"https://www.bhphotovideo.com/find/orderHistory.jsp/orderNumber","contactUsForm":"https://www.bhphotovideo.com/bnh/controller/home?O=index.jsp&A=customerService&Q=","imageAssets":"https://www.bhphotovideo.com/FrameWork/images","privacySecurity":"https://www.bhphotovideo.com/find/HelpCenter/PrivacySecurity.jsp","checkout":"https://www.bhphotovideo.com/bnh/controller/home?O=cart&A=cart&Q=update&createNewOrder=true&token=736a1882ab892a8b55d1737eb6038424","paypal":"https://www.bhphotovideo.com/bnh/controller/home?O=orderForm&A=expressCheckout&Q=paypal","googlePayLibrary":"https://pay.google.com/gp/p/js/pay","orderHistoryList":"https://www.bhphotovideo.com/bnh/controller/home?O=myAccount&A=orderHistory&Q=orderHistory","submitIovation":"https://www.bhphotovideo.com/find/submitIovation.jsp","accessories":"https://www.bhphotovideo.com/find/accessories.jsp","noResultsPage":"https://www.bhphotovideo.com/find/NoResultsPage.jsp","cpgStatic":"https://payment.bhphotovideo.com/static/","exploraBaseUrl":"www.bhphotovideo.com/explora","holidayShippingLink":"https://www.bhphotovideo.com/find/HelpCenter/holidayShippingCutoff.jsp","store":"https://www.bhphotovideo.com/find/HelpCenter/NYSuperStore08.jsp","home":"https://www.bhphotovideo.com","nonSecureAPI":"https://www.bhphotovideo.com/bnh/controller/home","litle":"https://paypage.bhphotovideo.com/","chat":"https://www.bhphotovideo.com/find/liveChat.jsp","giftCard":"https://www.bhphotovideo.com/find/giftCard.jsp","ask":"https://www.bhphotovideo.com/c/ask/","convertQuote":"https://www.bhphotovideo.com/bnh/controller/home?O=quote&A=convertQuote&Q=new&token=736a1882ab892a8b55d1737eb6038424","returnExchange":"https://www.bhphotovideo.com/find/HelpCenter/ReturnExchange.jsp","shippingRulesPolicies":"https://www.bhphotovideo.com/find/HelpCenter/int-shippingRulesPolicies.jsp","invoice":"https://www.bhphotovideo.com/find/invoice.jsp","myAccount":"https://www.bhphotovideo.com/find/MyAccount.jsp","iovation":"https://mpsnare.iesnare.com/snare"},"staticDomain":"https://www.bhphotovideo.com","litleForceBackup":"false","usedMode":false,"applePayMerchantIdentifier":"merchant.com.bhphoto","IPCountry":{"code":"US","name":"USA"},"googleInvisibleReCaptchaClient":"6Lf2djAUAAAAAMDBhvLo-XyoEBdzy9wmSi4-MV5j","isGsaMode":false,"disableSignInWithApple":false,"todayStoreHours":{"hourFormatedPickupOpeningTime":"10AM","date":"2021-04-12","pickupClose":"2021-04-12 20:00:00.0","dateFormatedPickupOpeningTime":"Monday, April 12","hourBeforeClosing":false,"formattedPickupClosingTime":"8:00 PM","formatedOpeningTime":"10:00 AM","storePickupOpen":false,"nowClosed":true,"nowOpen":false,"formattedPickupOpenTime":"10:00 AM","formatedPickupOpenAndCloseTime":"10am-8pm","opening":"2021-04-12 10:00:00.0","beforeOpen":true,"hourFormatedPickupClosingTime":"8PM","formatedClosingTime":"7:00 PM","formatedOpeningDate":"Monday, April 12","beforePickupOpen":true,"closing":"2021-04-12 19:00:00.0","todaysStoreHours":true,"storePickupClosed":true,"dayDateFormatedPickupOpeningTime":"Mon 4/12","pickupOpen":"2021-04-12 10:00:00.0"},"googlePaymentsMerchantID":"01211748221463468289","isUserFromTriState":false,"dlo":{"latitude":"37.75100","ib":false,"unfilteredBI":"","longitude":"-97.82200"},"showCustomerCallback":true,"salesForce_domain":"https://service.force.com","plccPromoting":{},"salesforce_liveagent_chat_url":"https://d.la2-c1-ia2.salesforceliveagent.com/chat","uri":"bnh/controller","isEduMode":false,"currentServerTime":1618206385283,"environment":"prod","secureUrlPrefix":"https://www.bhphotovideo.com","nonSecureUrlPrefix":"https://www.bhphotovideo.com","salesforce_org_id":"00D1a000000K8nw","facebookClientId":"626660050754608","hasBHAccount":false,"isAndroid":true,"showExpeditedShippingBanner":true,"user":{"hasEduAccount":false,"eduExpires":"","tollFreeNumber":"800.606.6969","isB2B":false,"isTaxExempt":false,"catalog":{"allowTaxExemptAndAccImport":false,"catalogId":2,"showNewB2bTemplate":false},"askForSchool":false,"isUnidaysVerified":false,"ib":false,"language":"E","eduSince":""},"isIos":false,"browsePath":"https://www.bhphotovideo.com/c/browse/","FREE_SHIPPING_MIN_ORDER":49},
        initialPayload: {"preloadHeroImage":"https://www.bhphotovideo.com/bimages/home-mobile@BHJ-68618_Brief_History.jpg","hasHomeBanner":true},
        constants: {
                PWA_SOURCE_PARAM: 'pwas',
                PWA_SOURCE_MOBILE_WEB: 'MobileWeb',
                PWA_SOURCE_ANDROID: 'Android'
        }
};

bnh.appyDesign = false;

if (window.performance && window.performance.mark)
        window.performance.mark('mark_index_start');


        window.forterSiteID = '07c0aec6173f';



Is there a way for me to somehow parse this text so that I can load only the "config" JSON portion of this text?

A quick and dirty way to do this would be a simple regex to grab the config portion of your string and load() it into Json .

import json
string = '''...'''
config = json.loads(re.search(r'(?<=config: ).*(?=,\n)', string).group())

config['appleSignInClientId']
#'com.bhphotovideo.signin'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM