Вернуть несколько предметов - PullRequest
0 голосов
/ 01 ноября 2018

Я новичок в Python, по сути, это мой первый проект на Python. Я использую ebaysdk для поиска электроники на ebay и хочу, чтобы он возвращал несколько результатов, потому что мое приложение предназначено для сравнения цен, но возвращает только один результат.

Кто-нибудь, пожалуйста, помогите мне заставить код возвращать несколько результатов.

Вот мой фрагмент кода.

@app.route('/ebay_page_post', methods=['GET', 'POST'])
def ebay_page_post():
    if request.method == 'POST':

        #Get json format of the text sent by Ajax
        search = request.json['search']

        try:
            #ebaysdk code starts here
            api = finding(appid='JohnOkek-hybridse-PRD-5c2330105-9bbb62f2', config_file = None)
            api_request = {'keywords':search, 'outputSelector': 'SellerInfo', 'categoryId': '293'}
            response = api.execute('findItemsAdvanced', api_request)
            soup = BeautifulSoup(response.content, 'lxml')

            totalentries = int(soup.find('totalentries').text)
            items = soup.find_all('item')

            for item in items:
                cat = item.categoryname.string.lower()
                title = item.title.string.lower().strip()
                price = int(round(float(item.currentprice.string)))
                url = item.viewitemurl.string.lower()
                seller = item.sellerusername.text.lower()
                listingtype = item.listingtype.string.lower()
                condition = item.conditiondisplayname.string.lower()

                print ('____________________________________________________________')

                #return json format of the result for Ajax processing
                return jsonify(cat + '|' + title + '|' + str(price) + '|' + url + '|' + seller + '|' + listingtype + '|' + condition)
        except ConnectionError as e:
            return jsonify(e)

Ответы [ 3 ]

0 голосов
/ 01 ноября 2018

На основе предоставленного вами кода добавлен пример набора пары ключ-значение, который вы можете использовать:

@app.route('/ebay_page_post', methods=['GET', 'POST'])
def ebay_page_post():
    if request.method == 'POST':

        #Get json format of the text sent by Ajax
        search = request.json['search']

        try:

            #ebaysdk code starts here
            api = finding(appid='JohnOkek-hybridse-PRD-5c2330105-9bbb62f2', config_file = None)
        api_request = {'keywords':search, 'outputSelector': 'SellerInfo', 'categoryId': '293'}
        response = api.execute('findItemsAdvanced', api_request)
        soup = BeautifulSoup(response.content, 'lxml')

        totalentries = int(soup.find('totalentries').text)
        items = soup.find_all('item')

        # This will be returned
        itemsFound = {}

        # This index will be incremented 
        # each time an item is added
        index = 0

        for item in items:
            cat = item.categoryname.string.lower()
            title = item.title.string.lower().strip()
            price = int(round(float(item.currentprice.string)))
            url = item.viewitemurl.string.lower()
            seller = item.sellerusername.text.lower()
            listingtype = item.listingtype.string.lower()
            condition = item.conditiondisplayname.string.lower()

            # Adding the item found in the collection
            # index is the key and the item json is the value
            itemsFound[index] = jsonify(cat + '|' + title + '|' + str(price) + '|' + url + '|' + seller + '|' + listingtype + '|' + condition)

            # Increment the index for the next items key
            index++

        for key in itemsFound: 
            print key, ':', itemsFound[key

        # return itemsFound

    except ConnectionError as e:
        return jsonify(e)
0 голосов
/ 22 ноября 2018

Я смог решить проблему.

Нажмите здесь, чтобы посмотреть, как я это сделал

Спасибо всем, кто внес свой вклад, я очень благодарен всем вам.

0 голосов
/ 01 ноября 2018

Как только первый предмет найден, добавьте его в коллекцию. После завершения цикла for верните коллекцию.

Прямо сейчас вы возвращаетесь (прерывая итерацию), как только нашли первое

...