【问题标题】:Scrape 'dictionary' type object from top of HTML file (bunch of text, not in a class)从 HTML 文件顶部刮取“字典”类型的对象(一堆文本,不在一个类中)
【发布时间】:2015-04-04 21:30:11
【问题描述】:

考虑以下源代码: 查看源代码:http://www.steepandcheap.com/gear-cache/shop-smartwool-on-sale/SWL00II-GRA

顶部有一个以“window.BC.product =”开头的字典/JSON类型文本

假设我有这个页面的一个汤对象。我将如何在顶部提取该文本并将其转换为 python 字典,以便从中提取特定数据?

【问题讨论】:

    标签: python python-2.7 web-scraping beautifulsoup scrapy


    【解决方案1】:

    通过检查 script 的文本是否包含“window.BC.product”来找到它。

    提取脚本内容后,使用正则表达式提取所需的javascript对象,然后通过json.loads()加载得到Python字典:

    import json
    import re
    from bs4 import BeautifulSoup
    import requests
    
    pattern = re.compile(r"window\.BC\.product = (.*);", re.MULTILINE)
    
    response = requests.get("http://www.steepandcheap.com/gear-cache/shop-smartwool-on-sale/SWL00II-GRA")
    soup = BeautifulSoup(response.content)   
    
    script = soup.find("script", text=lambda x: x and "window.BC.product" in x).text
    data = json.loads(re.search(pattern, script).group(1))
    print data
    

    打印:

    {u'features': [{u'name': u'Material', u'description': u'[shell] 86% polyester, ... u'Zippered back pocket\r', u'Reflective details']}
    

    【讨论】:

      猜你喜欢
      • 2017-10-12
      • 2013-12-05
      • 2021-03-13
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多