【发布时间】:2019-12-19 07:48:42
【问题描述】:
所以我在这里得到了一些不同的答案。是否使用正则表达式运行。
我想要做的是我试图在 html 中获取一个特定值(spConfig 的 json),即:
<script type="text/x-magento-init">
{
"#product_addtocart_form": {
"configurable": {
"spConfig": {"attributes":{"93":{"id":"93","code":"color","label":"Color","options":[{"id":"8243","label":"Helloworld","products":["97460","97459"]}],"position":"0"},"148":{"id":"148","code":"codish","label":"Codish","options":[{"id":"4707","label":"12.5","products":[]},{"id":"2724","label":"13","products":[]},{"id":"4708","label":"13.5","products":[]}],"position":"1"}},"template":"EUR <%- data.price %>","optionPrices":{"97459":{"oldPrice":{"amount":121},"basePrice":{"amount":121},"finalPrice":{"amount":121},"tierPrices":[]}},"prices":{"oldPrice":{"amount":"121"},"basePrice":{"amount":"121"},"finalPrice":{"amount":"121"}},"productId":"97468","chooseText":"Choose an Option...","images":[],"index":[]},
"gallerySwitchStrategy": "replace"
}
}
}
</script>
这就是问题所在。抓取 HTML 时,有多个 <script type="text/x-magento-init">,但只有一个 spConfig,我这里有两个问题。
我是否应该使用 Regex 获取值 spConfig 以便以后使用 json.loads(spConfigValue)?如果不是,那么我应该使用什么方法来抓取 json 值?
如果我应该使用正则表达式。我一直在尝试使用
\"spConfig\"\: (.*?)来抓取它,但它并没有为我抓取 json 值。我做错了什么?
【问题讨论】:
-
您在使用 BeautifulSoup 吗?还是您从 Splash 或使用 Selenium 无头刮取的动态加载的 javascript?如果用汤:stackoverflow.com/questions/26192727/…
-
@mgrollins 抱歉没有提及!我正在使用 BeautifulSoup
bs4 = soup(requests.text, 'html.parser'),后来我使用for values in bs4.find_all('script', {'type': 'text/x-magento-init'}): -
好的,太好了!检查该答案,看起来您可以通过负载将
values转换为json:data = json.loads(values.text),然后测试spConfig是否是数据中的键,然后使用属性。 -
@mgrollins Yupp 我做到了 :) 但是现在我在获取正确的 .items() 值时遇到了问题,但这个问题不适合这里,因为这是别的东西:)
-
我会用 json 加载它,然后使用 Try/Catch 访问正确的脚本标签,如果还没有新标签,我会输入一些内容作为答案。