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