как извлечь строку или число из bs4.element.NavigableString - PullRequest
0 голосов
/ 29 августа 2018

Это мой код:

soup_detail.find_all ( "сценарий", тип = "приложения / LD + JSON") [0] .contents [0]

Это вывод вышеуказанного кода:

'{"@context": "http://schema.org"," @type ":" Product ", "name": "Мужские тапочки. Краткий дизайн. Заклепки. Декор All Match Fashion" Носимая обувь "," image ":" "," description ":" Материал: искусственная кожа ", "brand": {"@type": "Thing", "name": ""}, "aggregateRating": { "@type": "AggregateRating", "ratingValue": "5", "reviewCount": "1"}, "предложения": {"@type": "предложение", "доступность": "http://schema.org/InStock"," цена ":" 10.99 "," цена валюта ":" доллар США " }} '

Как мне извлечь, например, "ratingValue": "5", "reviewCount": "1" из этого bs4.element.NavigableString?

Заранее спасибо за помощь.

Ответы [ 2 ]

0 голосов
/ 29 августа 2018
import json

d = '{ "@context": "http://schema.org", "@type": "Product", "name":"Men\'s Slippers Brief Design Rivet Decor All Match Fashion Wearable Shoes", "image":"", "description": "Material:Faux Leather", "brand":{ "@type": "Thing", "name": "" }, "aggregateRating": { "@type": "AggregateRating", "ratingValue": "5", "reviewCount": "1" }, "offers": { "@type": "Offer", "availability": "http://schema.org/InStock", "price": "10.99", "priceCurrency": "USD" } }'
data = json.loads(d)
print(data['aggregateRating']['reviewCount']) #1
print(data['aggregateRating']['ratingValue']) #5
0 голосов
/ 29 августа 2018
j = '{ "@context": "http://schema.org", "@type": "Product", "name":"Men\'s Slippers Brief Design Rivet Decor All Match Fashion Wearable Shoes", "image":"", "description": "Material:Faux Leather", "brand":{ "@type": "Thing", "name": "" }, "aggregateRating": { "@type": "AggregateRating", "ratingValue": "5", "reviewCount": "1" }, "offers": { "@type": "Offer", "availability": "http://schema.org/InStock", "price": "10.99", "priceCurrency": "USD" } }'
j = json.loads(j)
print(j['@context'])
print(j['aggregateRating']['reviewCount'])
print(j['aggregateRating']['ratingValue'])
print(j.keys())
print(j.values())

выход

http://schema.org
1
5
dict_keys(['@context', '@type', 'name', 'image', 'description', 'brand', 'aggregateRating', 'offers'])
dict_values(['http://schema.org', 'Product', "Men's Slippers Brief Design Rivet Decor All Match Fashion Wearable Shoes", '', 'Material:Faux Leather', {'@type': 'Thing', 'name': ''}, {'@type': 'AggregateRating', 'ratingValue': '5', 'reviewCount': '1'}, {'@type': 'Offer', 'availability': 'http://schema.org/InStock', 'price': '10.99', 'priceCurrency': 'USD'}])
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...