запись словарей из двух разных ссылок

from PyQt5.Qt import *
from pickle import TRUE
import requests
from bs4 import BeautifulSoup
import json



class ThreadM(QThread):
    stepChanged = pyqtSignal(int, int)
    finished = pyqtSignal(list)
    error = pyqtSignal(str)

    def __init__(self, url, file, HEADERS):
        super().__init__()
        self.url = url
        self.file = file
        self.HEADERS = HEADERS


    def run(self):        
        self.parseM()
        
    def parseM(self):

        html = self.get_html()
        if not html:
            if html != False:
                self.error.emit(
                    f'Error: status_code={html.status_code}'
                )
            return
        
        if html.status_code == 200:
            products = []
            pages_count = self.get_pages_count(html.text)
            for page in range(1, pages_count + 1):
                self.stepChanged.emit(page, pages_count)
                
                html = self.get_html(params={'page': page})
                products.extend(self.get_content(html.text))
                self.msleep(50)
                
            self.finished.emit(products)

        else: 
            self.error.emit(f'Error: status_code={html.status_code}')

    def get_html(self, params=None):
        try:
            r = requests.get(self.url, headers=self.HEADERS, params=params)
            return r 
        except:
            self.error.emit(f'Error: Что-то пошло не так.')
            return False

    def get_pages_count(self, html):
        soup = BeautifulSoup(html, 'html.parser')
        pagination = soup.select('span.block')
        if pagination:
            return int(pagination[-1].get_text().replace('\n', ''))
        else:
            return 1

    def get_content(self, html):
        rl = requests.get(self.url)

        
    
        product_ids = ','.join(str(x['id']) for x in rl.json()['data']['items'])


        data = {
        'product_ids': product_ids
        }

        rs = requests.post('https://www.mechta.kz/api/new/mindbox/actions/catalog', data=data).json()['data']

        products = []
        for j in rl.json()['data']['items']:
            title = j['title']   
            products.append({
                'title': title
            })
        
        for item,k in rs.items():
            price = k['prices']['discounted_price']
            old_price = k['prices']['base_price']
            if old_price == price:
                old_price = 'Скидки нет'
            
            products.append({
            'price': price,
            'old price': old_price
        })    

        return products

Вот имеется код, не могу понять как записать данные в массив из двух разных ссылок

ссылка get запроса вот https://www.mechta.kz/api/new/catalog?properties=&page=2&section=smartfony


Ответы (1 шт):

Автор решения: D.Vinogradov

В Вашем случае у Вас получается не очень удобный вид списка со словарями. Сперва идут все title, затем группы price , old_price.

>>>
[{'title': ...}, {'title': ...}, {'title': ...}, ...{'price': ... , 'old_price': ...}, {'price': ..., 'old_price': ...}]

На мой взгляд работать с этим в последующем будет не очень удобно. Лучше все сделать в одном, вместе с product_id.

Предлагаю Вам немного изменить функцию get_content()

def get_content(self, html):
    rl = requests.get(self.url)

    data = []
    for j in rl.json()['data']['items']:
        title = j['title']
        ids = j['id']
        data.append({
            'product_ids': ids,
            'title': title
        })
    
    data = sorted(data, key=lambda x: x['product_ids'])
    res = {'product_ids': ','.join(str(i.get('product_ids')) for i in data)}

    rs = requests.post('https://www.mechta.kz/api/new/mindbox/actions/catalog', data=res).json()['data']

    data2 = []
    for item, k in rs.items():
        price = k['prices']['discounted_price']
        old_price = k['prices']['base_price']
        if old_price == price:
            old_price = 'Скидки нет'

        data2.append({
            'price': price,
            'old price': old_price
        })

    return [{**x, **y} for x, y in zip(data, data2)]

У Вас получается по итогу 2 списка словарей, которые Вы в конечном итоге соединяете.

Получается что-то вроде этого:

[{'product_ids': 5, 'title': 'Телефон сотовый SAMSUNG SM F 916 Galaxy Z Fold 2 256gb BZNQSKZ (Bronze)', 'price': 399990, 'old price': 999890}...]
→ Ссылка