Вопрос Выбивает ошибку JSONDecodeError парсер cian

И шо тут писать?:)
Начинающий
Статус
Оффлайн
Регистрация
5 Апр 2020
Сообщения
79
Реакции[?]
11
Поинты[?]
0
1. файл который запускаю
Python:
from datetime import datetime
import requests
from getDb import check_database


def get_offer(item):
    offer = {"url": item["fullUrl"], "offer_id": item["id"]}

    timestamp = datetime.fromtimestamp(item["addedTimestamp"])
    timestamp = datetime.strftime(timestamp, '%Y-%m-%d %H:%M:%S')
    offer["date"] = timestamp

    offer["price"] = item["bargainTerms"]["priceRur"]
    offer["address"] = item["geo"]["userInput"]
    offer["area"] = item["totalArea"]
    offer["rooms"] = item["roomsCount"]
    offer["floor"] = item["floorNumber"]
    offer["total_floor"] = item["building"]["floorsCount"]

    return offer


def get_offers(data):
    for item in data["data"]["offersSerialized"]:
        offer = get_offer(item)
        check_database(offer)
        # break


def get_json():
    headers = {
        'authority': 'api.cian.ru',
        'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"',
        'sec-ch-ua-mobile': '?0',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36',
    }
    data = '{"jsonQuery":{"sort":{"type":"term","value":"creation_date_desc"},"is_by_homeowner":{"type":"term","value":true},"_type":"flatsale","room":{"type":"terms","value":[1,2,3,4,5,6]},"region":{"type":"terms","value":[4623]},"engine_version":{"type":"term","value":2}}}'
    response = requests.post('https://api.cian.ru/search-offers/v2/search-offers-desktop/', headers=headers, data=data)
    result = response.json()
    return result


def main():
    data = get_json()
    get_offers(data)


if __name__ == '__main__':
    while True:
        main()
2. файл в котором лежит функция check_database
Python:
import sqlite3
import requests
from config import token, chat_id


def check_database(offer):
    offer_id = offer["offer_id"]
    with sqlite3.connect('realty.db') as connection:
        cursor = connection.cursor()
        cursor.execute("""
            SELECT offer_id FROM offers WHERE offer_id = (?)
        """, (offer_id,))
        result = cursor.fetchone()
        if result is None:
            send_telegram(offer)
            cursor.execute("""
                INSERT INTO offers
                VALUES (NULL, :url, :offer_id, :date, :price,
                    :address, :area, :rooms, :floor, :total_floor)
            """, offer)
            connection.commit()
            print(f'Объявление {offer_id} добавлено в базу данных')


def format_text(offer):
    title = f"{offer['rooms']}, {offer['area']} м2, {offer['floor']}/{offer['total_floor']} эт."

    d = offer['date']
    date = f"{d[8:10]}.{d[5:7]} в {d[11:16]}"

    text = f"""{offer['price']} ₽
<a href='{offer['url']}'>{title}</a>
{offer['address']}
{date}"""

    return text


def send_telegram(offer):
    text = format_text(offer)
    url = f'https://api.telegram.org/bot{token}/sendMessage'
    data = {
        'chat_id': chat_id,
        'text': text,
        'parse_mode': 'HTML'
    }
    response = requests.post(url=url, data=data)
    print(response)


def main():
    pass


if __name__ == '__main__':
    main()
так вот вопрос, как зафиксить эту ошибку?
1645608557528.png
 
Пользователь
Статус
Оффлайн
Регистрация
17 Мар 2021
Сообщения
400
Реакции[?]
102
Поинты[?]
0
1. файл который запускаю
Python:
from datetime import datetime
import requests
from getDb import check_database


def get_offer(item):
    offer = {"url": item["fullUrl"], "offer_id": item["id"]}

    timestamp = datetime.fromtimestamp(item["addedTimestamp"])
    timestamp = datetime.strftime(timestamp, '%Y-%m-%d %H:%M:%S')
    offer["date"] = timestamp

    offer["price"] = item["bargainTerms"]["priceRur"]
    offer["address"] = item["geo"]["userInput"]
    offer["area"] = item["totalArea"]
    offer["rooms"] = item["roomsCount"]
    offer["floor"] = item["floorNumber"]
    offer["total_floor"] = item["building"]["floorsCount"]

    return offer


def get_offers(data):
    for item in data["data"]["offersSerialized"]:
        offer = get_offer(item)
        check_database(offer)
        # break


def get_json():
    headers = {
        'authority': 'api.cian.ru',
        'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"',
        'sec-ch-ua-mobile': '?0',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36',
    }
    data = '{"jsonQuery":{"sort":{"type":"term","value":"creation_date_desc"},"is_by_homeowner":{"type":"term","value":true},"_type":"flatsale","room":{"type":"terms","value":[1,2,3,4,5,6]},"region":{"type":"terms","value":[4623]},"engine_version":{"type":"term","value":2}}}'
    response = requests.post('https://api.cian.ru/search-offers/v2/search-offers-desktop/', headers=headers, data=data)
    result = response.json()
    return result


def main():
    data = get_json()
    get_offers(data)


if __name__ == '__main__':
    while True:
        main()
2. файл в котором лежит функция check_database
Python:
import sqlite3
import requests
from config import token, chat_id


def check_database(offer):
    offer_id = offer["offer_id"]
    with sqlite3.connect('realty.db') as connection:
        cursor = connection.cursor()
        cursor.execute("""
            SELECT offer_id FROM offers WHERE offer_id = (?)
        """, (offer_id,))
        result = cursor.fetchone()
        if result is None:
            send_telegram(offer)
            cursor.execute("""
                INSERT INTO offers
                VALUES (NULL, :url, :offer_id, :date, :price,
                    :address, :area, :rooms, :floor, :total_floor)
            """, offer)
            connection.commit()
            print(f'Объявление {offer_id} добавлено в базу данных')


def format_text(offer):
    title = f"{offer['rooms']}, {offer['area']} м2, {offer['floor']}/{offer['total_floor']} эт."

    d = offer['date']
    date = f"{d[8:10]}.{d[5:7]} в {d[11:16]}"

    text = f"""{offer['price']} ₽
<a href='{offer['url']}'>{title}</a>
{offer['address']}
{date}"""

    return text


def send_telegram(offer):
    text = format_text(offer)
    url = f'https://api.telegram.org/bot{token}/sendMessage'
    data = {
        'chat_id': chat_id,
        'text': text,
        'parse_mode': 'HTML'
    }
    response = requests.post(url=url, data=data)
    print(response)


def main():
    pass


if __name__ == '__main__':
    main()
так вот вопрос, как зафиксить эту ошибку?
Посмотреть вложение 193629
по моему твой json пустой
 
ставь чайник, зажигай плиту
Эксперт
Статус
Оффлайн
Регистрация
22 Май 2020
Сообщения
1,442
Реакции[?]
1,092
Поинты[?]
10K
у тебя result пустой приходит
 
Сверху Снизу