Как сохранить каждый вывод из a для l oop в словаре - PullRequest
0 голосов
/ 20 февраля 2020

Я не могу понять, как получить все выходные значения в моем dict. Когда я запускаю свой код, я получаю только последний вывод, но если я использую print для for l oop, чтобы проверить, я вижу, что собираю больше выходов.

Моя цель - получить все выходы и не только последний.

КОД:

def cointelegraph():
    for div in soup.find_all('div', class_='post-preview-item-inline'):
        content = dict()
        title = div.find(class_='post-preview-item-inline__title').get_text()
        #print(title)
        content['title'] = title
        body = div.find(class_='post-preview-item-inline__text').get_text()
        #print(body)
        content['body'] = body
        for links in div.select('.post-preview-item-inline__figure-link'):
            link = links.get('href')
            #print(link)
            content['link'] = link
            content['total_body'] = body + '\n \n' +' Link to article: ' + link

    return content


#make_post(cointelegraph())
print(cointelegraph())

РЕЗУЛЬТАТ:

{'title': ' Bitcoin Price Reclaims $10K Reversing Weekend Losses, XTZ Soars 13% ', 'body': ' Bitcoin price briefly reclaimed $10K after a bearish weekend which saw the creation of a new CME gap at $10,460. ', 'link': 'https://cointelegraph.com/news/bitcoin-price-reclaims-10k-reversing-weekend-losses-xtz-soars-13', 'total_body': ' Bitcoin price briefly reclaimed $10K after a bearish weekend which saw the creation of a new CME gap at $10,460. \n \n Link to article: https://cointelegraph.com/news/bitcoin-price-reclaims-10k-reversing-weekend-losses-xtz-soars-13'}

Source HTML

1 Ответ

1 голос
/ 20 февраля 2020

Вы используете неправильную структуру данных и в неправильном месте. Попробуйте что-то вроде ниже

def cointelegraph():
    all_content = []

    for div in soup.find_all('div', class_='post-preview-item-inline'):
        content = dict()
        title = div.find(class_='post-preview-item-inline__title').get_text()
        #print(title)
        content['title'] = title
        body = div.find(class_='post-preview-item-inline__text').get_text()
        #print(body)
        content['body'] = body
        content['links'] = []
        for links in div.select('.post-preview-item-inline__figure-link'):
            link = links.get('href')
            #print(link)
            content['links'].append({"link": link, 'total_body': body + '\n \n' +' Link to article: ' + link})

        all_content.append(content)
    return all_content
...