Как извлечь словарь / список из BeautifulSoup - PullRequest
0 голосов
/ 14 января 2020

С помощью следующей строки кода я могу извлечь строку, подобную списку, с Beautifulsoup

Код:

section = soup.find("div", {"class": "listing-col col-sm-16 col-md-12 col-lg-13 col"})

for span in section.select('div.carListing--textCol2'):
    print(span.select_one('shortlist-directive[ng-init]')['ng-init'])

Там, где выходные данные дают список esque dictionary-esque line

Вывод:

setCurrentListingIdSrp('10856566'); setGAEventDataSrp({"ss_cg_listing_id":10856566,"listingid":10856566,"make":"Audi","model":"A4","transmission":"Manual","body_type":"Wagon","location":"the moon, SolarSystem","Kms":"12,469 km","featured":"No","seller_type":"USED Dealer ad","ss_cg_products":"V"});

Вопрос:

Как извлечь setGAEventDataSrp как Python словарь?

То, что я пробовал, но не работало:

Не самый Pythoni c способ.

for span in section.select('div.carListing--textCol2'):
        data_string = dict(str(span.select_one('shortlist-directive[ng-init]')['ng-init'].split('setGAEventDataSrp(')[-1][:-2]))

Ответы [ 2 ]

1 голос
/ 14 января 2020

Используйте регулярное выражение.

import re
import json
html='''setCurrentListingIdSrp('10856566'); setGAEventDataSrp({"ss_cg_listing_id":10856566,"listingid":10856566,"make":"Audi","model":"A4","transmission":"Manual","body_type":"Wagon","location":"the moon, SolarSystem","Kms":"12,469 km","featured":"No","seller_type":"USED Dealer ad","ss_cg_products":"V"});'''
output=re.findall('\{.*?}',html)[0]
json=json.loads(output)
print(json)

Просто замените html на span.select_one('shortlist-directive[ng-init]')['ng-init']

1 голос
/ 14 января 2020

Можно использовать json.loads

>>> import json
>>> type(json.loads('{"a":1, "b":"w"}'))
<class 'dict'>

А

data_string = json.loads(str(span.select_one('shortlist-directive[ng-init]')['ng-init']).split('setGAEventDataSrp(')[-1][:-2])
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...