我是新与BeautifulSoup到webscraping并想提取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
是的,你可以将它保存为一个字典(或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
提高对答案。下面的代码为您提供了必要的词典,从中你可以访问问题的所需信息,更轻松地不是依赖于原来的嵌套字典。
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€'},
......
}
您可能会再次jsonify输出使用
json_output = json.dumps(desired_data)