python - 用 Beautiful soup 解析 JS

标签 python web-scraping html-parsing beautifulsoup

我用漂亮的汤解析了一些页面。但是我有 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>

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

谢谢

最佳答案

一旦你通过脚本文本

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... 的顺序返回名称和值的列表,您可以随意修改或稍后将其转换为字典。

关于python - 用 Beautiful soup 解析 JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24333189/

相关文章:

python - 为什么 lxml 在 Python 中有时(但不常见)会抛出错误?

python - 网页抓取 : How to test if the root tag has a particular CSS class?

html - 如何使用 Swift 访问 Kanna 中的特定标签?

reactjs - 无法解析安装 html-parser 的依赖关系

python - 灵活性问题 : Index Variables vs. 常量

python - 过滤 Pandas 数据框聚合

python - 如何将 pandas DataFrame 转换为字节,反之亦然?

python - 按一个键的值对mongodb进行排序

python - Beautifulsoup 与 lxml vs Beautifulsoup 3

带有 jsessionid 的 R 网络爬虫