【问题标题】:Parsing JS with Beautiful soup用美丽的汤解析 JS
【发布时间】:2014-08-11 13:27:52
【问题描述】:

我用漂亮的汤解析了一些页面。但是我有js代码:

<script type="text/javascript">   


var utag_data = {
            customer_id   : "_PHL2883198554", 
            customer_type : "New",
            loyalty_id : "N",
            declined_loyalty_interstitial : "false",
            site_version  : "Desktop Site",
            site_currency: "de_DE_EURO",
            site_region: "uk",
            site_language: "en-GB",


            customer_address_zip : "",
            customer_email_hash :  "",
            referral_source :  "",
            page_type : "product",
            product_category_name : ["Lingerie"],
            product_category_id :[jQuery("meta[name=defaultParent]").attr("content")],
            product_id : ["5741462261401"],
            product_image_url : ["http://images.urbanoutfitters.com/is/image/UrbanOutfitters/5741462261401_001_b?$detailmain$"],
            product_brand : ["Pretty Polly"],
            product_selling_price : ["20.0"],
            promo_id : "6",
            product_referral : ["WOMENS-SHAPEWEAR-LINGERIE-SOLUTIONS-EU"],
            product_name : ["Pretty Polly Shape It Up Tummy Shaping Camisole"],
            is_online_only : true,
            is_back_in_stock : false
}
</script>

如何从该输入中获取一些值? 我应该像处理文本一样处理这个例子吗?我的意思是把它写入一些变量并拆分然后获取一些数据?

谢谢

【问题讨论】:

    标签: python web-scraping html-parsing beautifulsoup


    【解决方案1】:

    一旦你通过

    获得了脚本的文本
    js_text = soup.find('script', type="text/javascript").text
    

    例如。然后你可以使用正则表达式来查找数据,我相信有一个更简单的方法可以做到这一点,但正则表达式应该也不难。

    import re
    regex =  re.compile('\n^(.*?):(.*?)$|,', re.MULTILINE) #compile regex
    js_text = re.findall(regex, js_text) #  find first item @ new line to : and 2nd item @ from : to the end of the line or , 
    js_text = [jt.strip() for jt in js_text] #  to strip away all of the extra white space.
    

    这将返回 name|value|name2|value2... 顺序中的名称和值列表,您可以在以后随意处理或转换为字典。

    【讨论】:

    • @user3761151 添加 re.MULTILINE 标志,忘记提及了。编辑了我的答案。您可以在此处找到如何在 Python 中使用正则表达式的完整文档:docs.python.org/3.4/library/re.html
    • 但是如果我需要这样的字符串:this.products = ko.observableArray([{"productId":537477, ... elemets }]) ,是否可以为它制作正则表达式?
    • @user3761151 我无法理解您在这里实际需要什么,但是使用正则表达式,您几乎可以从获得的字符串中提取任何您想要的东西。了解正则表达式对于任何字符串管理工作都至关重要,因此我强烈建议您花一两个晚上的时间来学习它。
    猜你喜欢
    • 2013-04-29
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    相关资源
    最近更新 更多