使用BeautifulSoup获取信息并使其可提取

时间:2019-02-05 09:26:40

标签: python web-scraping beautifulsoup

我不喜欢使用BeautifulSoup进行网络抓取,并且想从zalando.de中提取一些信息。

我已经找到了我所需的信息(价格,货号,...)所在的行。是否可以将该行另存为可访问的数据类型(例如字典)以通过其键提取信息?

from bs4 import BeautifulSoup
import requests

source = requests.get("https://en.zalando.de/carhartt-wip-hooded-chase-sweatshirt-c1422s02x-g13.html?_rfl=de").text
soup = BeautifulSoup(source, "lxml")
scr = soup.find("script", id = "z-vegas-pdp-props").text

2 个答案:

答案 0 :(得分:1)

是的,您可以将其另存为字典(确切地说是JSON)。您可以使用json模块将字符串转换为json。

首先需要将文本转换为有效的json。您可以通过删除无效部分来做到这一点。

from bs4 import BeautifulSoup
import requests
import json

source = requests.get("https://en.zalando.de/carhartt-wip-hooded-chase-sweatshirt-c1422s02x-g13.html?_rfl=de").text
soup = BeautifulSoup(source, "lxml")
scr = soup.find("script", id = "z-vegas-pdp-props").text

data = json.loads(scr.lstrip('<![CDATA').rstrip(']>'))
print(data['layout'])
# cover

答案 1 :(得分:0)

改善答案。下面的代码为您提供了所需的字典,从中可以轻松地从问题中获得所需的信息,而不是依赖于原始的嵌套字典。

from bs4 import BeautifulSoup
import requests
import json

source = requests.get("https://en.zalando.de/carhartt-wip-hooded-chase-sweatshirt-c1422s02x-g13.html?_rfl=de").text
soup = BeautifulSoup(source, "lxml")
scr = soup.find("script", id = "z-vegas-pdp-props").text

data = json.loads(scr.lstrip('<![CDATA').rstrip(']>'))
desired_data = dict(data['model']['articleInfo'])
print(desired_data)

输出看起来像这样。

{'modelId': 'C1422S02X',
 'id': 'C1422S02X-G13',
 'shopUrl': 'https://en.zalando.de/carhartt-wip-hooded-chase-sweatshirt-c1422s02x-g13.html',
 'sizeFits': None,
 'commodity_group': {'values': ['2', '2', 'S', '4']},
 'active': True,
 'name': 'HOODED CHASE  - Hoodie - cranberry/gold',
 'color': 'cranberry/gold',
 'silhouette_code': 'pullover',
 'product_group': 'clothing',
 'category_tag': 'Sweatshirt',

......
'price': {'currency': 'EUR', 'value': 74.95, 'formatted': '74,95\xa0€'},
......
}

您可以使用

再次对输出进行json处理
json_output = json.dumps(desired_data)
相关问题