예제 #1
0
from ebaysdk.finding import Connection as Finding
from ebaysdk.exception import ConnectionError

keyword = input()

try:
    api = Finding(config_file='config.py')
    response = api.execute('findItemsAdvanced', {'keywords': keyword})
    results = response.dict()
    items = results['searchResult']['item']
    for item in items:
        print(item)
except ConnectionError as e:
    print(e)
    print(e.response.dict())
예제 #2
0
def ebay_search(keywords, filters, workbook, tkname):

    for keyword in keywords.keys():
        id_dict = {}
        r = 0
        workbook.create_worksheet(keyword)
        api = Finding(appid="********", config_file=None)
        response = api.execute('findItemsAdvanced', {'keywords': keyword})
        soup = bs4.BeautifulSoup(response.content, 'lxml')
        items = soup.find_all('item')

        for item in items:
            title = item.title.string
            url = item.viewitemurl.string
            item_price = item.currentprice.string
            ship_type = item.shippingtype.string
            list_type = item.listingtype.string
            condition = item.conditiondisplayname.string
            item_id = item.itemid.string
            try:
                ship_price = item.shippingservicecost.string
            except:
                ship_price = 'error'
            try:
                post_code = item.postalcode.string
            except:
                post_code = 'N/A'
            if 'error' in ship_price.lower():
                total_price = float(item_price)
            else:
                total_price = float(item_price) + float(ship_price)

            price_limit = keywords[keyword]['price_param']
            stock_limit = keywords[keyword]['stock_param']
            rows = [
                keyword, title, url, item_price, ship_type, list_type,
                condition, item_id, ship_price, post_code, total_price
            ]
            row_names = [
                'keyword', 'title', 'url', 'item_price', 'ship_type',
                'list_type', 'condition', 'item_id', 'ship_price', 'post_code',
                'total_price'
            ]

            discard = discard_logic(filters, title, total_price, condition,
                                    price_limit)

            if discard == False:
                id_dict[url] = dict(zip(row_names, rows))

        row_names.append('stock')
        workbook.xlsx_write(row_names)
        session = requests.Session()
        for url in id_dict.keys():
            stock = stock_search(url, session)
            stock = stock.replace(",", "")
            print(str(id_dict[url]['url']))

            print(str(stock))
            if int(stock) >= stock_limit:
                r += 1
                id_dict[url]['stock'] = int(stock)
                rows = []
                for value in id_dict[url].values():
                    rows.append(value)
                workbook.xlsx_write(rows, r)
            tkname.after(random.randint(5000, 10000), passit())

    print('DONE')
예제 #3
0
	backend='amqp://')

logger = get_task_logger(__name__)

env_app_id = os.environ['EBAY_PRODUCTION_APP_ID']

s_api = Shopping(
	domain="open.api.ebay.com",
	appid=env_app_id,
	config_file=None,
	debug=False
)

f_api = Finding(
	domain="svcs.ebay.com",
	appid=env_app_id,
	config_file=None,
	debug=False)


@celery.task(bind=True)
def create_item_model(
	self,
	json_api_response,
	ebay_seller_id=None,
	with_measurements=False,
	with_sizes=False,
	affiliate_url=None):
	"""Celery task wrapper for model_builders.build_ebay_item_model."""

	api_response = loads(json_api_response)
예제 #4
0
from ebaysdk.finding import Connection as Finding
from ebaysdk.shopping import Connection as Shopping
from ebaysdk.trading import Connection as Trading
from ebaysdk.exception import ConnectionError

import requests
import csv
import math
import sys

ID_APP = 'BarSowka-book-PRD-98dfd86bc-88e04dff'

finding_api = Finding(appid=ID_APP, config_file=None)
shopping_api = Shopping(appid=ID_APP, config_file=None)
trading_api = Trading(appid=ID_APP, config_file=None)

conditionsDict = {
    'Brand new': 1000,
    'Like new': 3000,
    'Very Good': 4000,
    'Good': 5000,
    'Acceptable': 6000,
}

listingTypes = [
    'Auction', 'AuctionWithBIN', 'Classified', 'FixedPrice', 'StoreInventory',
    'All'
]
sortOrders = [
    'BestMatch', 'BidCountFewest', 'BidCountMost', 'CountryAscending',
    'CountryDescending', 'CurrentPriceHighest', 'DistanceNearest',
예제 #5
0
from config import EBAY_API_KEY
from ebaysdk.finding import Connection as Finding
from ebaysdk.exception import ConnectionError

try:
    api = Finding(appid=EBAY_API_KEY, config_file=None)
    response = api.execute('findItemsAdvanced', {'keywords': 'iphone'})
    dictr = response.dict()
    print(dictr)

except ConnectionError as e:
    print(e)
    print(e.response.dict())
예제 #6
0
파일: test_search.py 프로젝트: jsl12/Ebay
import sys
from ebaysdk.finding import Connection as Finding
from ebaysdk.exception import ConnectionError
from accounts import PRODUCTION_APPID
from ebay_processing import response_to_dataframe

# Get the search query from the command line.
query_arg = sys.argv[1]

# Add error checking for empty string.

# Converts the query argument into a variable called query
exec('query = search_queries.' + query_arg.lower())

# Add error checking to make sure query_arg matches something and that query isn't an empty string.

try:
    api = Finding(appid=PRODUCTION_APPID, config_file=None)
    response = api.execute('findCompletedItems', query)
    df = response_to_dataframe(response)
    print(df.head())
    df.to_excel('Results_' + query_arg + '.xlsx',
                sheet_name='Results',
                index=False)
except ConnectionError as e:
    print(e)
    print(e.response.dict())
예제 #7
0
        if not match:
            continue
        seval.names = {
            **match.groupdict(),
            **simpleeval.DEFAULT_NAMES, 'price': item.price
        }
        logger.info(f"Evaluating item {item}, match {match}")
        try:
            return seval.eval(value_expression)
        except Exception as e:
            logger.warning(f"Ignoring exception: {e}")
            return math.inf
    return 0


ebay_api = Finding(appid="", config_file=None, warnings=True, https=True)


def _ebay_search(keywords):
    for pageNumber in range(1, 4 + 1):
        response = ebay_api.execute('findItemsAdvanced', {
            'keywords': keywords,
            'paginationInput': {
                'pageNumber': pageNumber,
            }
        })
        for item in response.reply.searchResult.item:
            try:
                if item.isMultiVariationListing == 'true':
                    logger.info(
                        "Skipping a MultiVariationListing because handling it is too much work."
예제 #8
0
from ebaysdk.finding import Connection as Finding

ebay_api = Finding(domain='svcs.ebay.com',
                   config_file=None,
                   appid="DatNguye-simpleca-PRD-0c8ee5576-eb7ef499",
                   siteid="EBAY-US")
a = ebay_api.execute("findItemsByProduct")
print()
예제 #9
0
import ebaysdk
from ebaysdk.exception import ConnectionError

#connection is mainly to retrieve the Finding API connection keys stored in a yaml file
#from ebaysdk.finding import connection
from ebaysdk.finding import Connection as Finding
import json


#if __name__ == '__main__':
 #   api = Connection(config_file='ebay.yaml', debug=True, siteid="EBAY-US")

api = Finding(domain='svcs.ebay.com',
              appid="NareshKa-ProductD-PRD-1a6d0a603-d5eebc0b", config_file=None)

# Go through the below link to understand the key words concept
#https://linuxconfig.org/introduction-to-ebay-api-with-python-the-finding-api-part-2
# https://developer.ebay.com/devzone/finding/CallRef/index.html

response = api.execute('findItemsByKeywords', {'keywords': 'handbags'})
#response.status_code or response.raise_for_status()
output = response.dict()
output["searchResult"]["item"]
#data_serialization = json.dump(output, open('data.json',"w"), indent = 4)
# sample data to view
#for item in response.reply.searchResult.item:
# print(f"Title: {item.title}, Price: {item.sellingStatus.currentPrice.value}")

#declaring arrays to store response data
product_list=[]
shipping_type=[]
예제 #10
0
from search_queries import hammond_b3

api = 'findCompletedItems'
query = 'hammond_b3'
excel_file = api + '-' + query + '.xlsx'

# Read the existing data from the Excel file into a DataFrame.
xlsx = pd.ExcelFile(excel_file)
df1 = pd.read_excel(xlsx, query, index_col=None, na_values=['NA'])
#print(df1.head())
#print(list(df1.columns))
#print(df1.itemId.values)

# Query the API and store the results into a second DataFrame.
try:
    api = Finding()
    response = api.execute('findCompletedItems', hammond_b3)
    # Note: I suspect that this API query is only returning the first 100 items.

    df2 = response_to_dataframe(response)
    #print(df2.head())

except ConnectionError as e:
    print(e)
    print(e.response.dict())

# Add only the newly found items to the first DataFrame.
for index, row in df2.iterrows():
    #print(row['itemId'])

    # Test to see if the itemId already exists in first DataFrame. If not, then add it.
예제 #11
0
def ebayFunction():
    api = Finding(config_file=None,
                  domain='svcs.ebay.com',
                  appid="SatyaPra-MyEBPrac-PRD-abce464fb-dd2ae5fe",
                  devid="6c042b69-e90f-4897-9045-060858248665",
                  certid="PRD-bce464fbd03b-273a-4416-a299-7d41")

    items = list()

    inputObj = {
        "itemFilter": {
            "name": "Seller",
            "value": ""
        },
        "OutputSelector": [
            "Title", "itemId", "ViewItemURL", "SellingStatus",
            "ListingDuration", "listingInfo"
            "StartTime", "EndTime", "WatchCount", "ItemsPerPage",
            "PrimaryCategory", "HasMoreItems", "PageNumber",
            "ReturnedItemCountActual", "PaginationResult"
        ],
        "StartTimeFrom":
        "",
        "StartTimeTo":
        "",
        "IncludeWatchCount":
        "true",
        "paginationInput": {
            "entriesPerPage": "100",
            "pageNumber": "0"
        }
    }

    startDateTo = datetime.datetime.now()
    startDateFrom = startDateTo - datetime.timedelta(15)
    sellerIdFromSheet, noOfMonths = getFromSheet()
    logger.debug(f"seller id fro sheet  {sellerIdFromSheet}")
    logger.debug(f"no of months {str(noOfMonths)}")
    if sellerIdFromSheet is not None and len(sellerIdFromSheet) > 0:

        inputObj["itemFilter"]["value"] = sellerIdFromSheet
        # queryRepeats = int(noOfMonths / 3)
        # if (noOfMonths == 1):  # one month only
        #     queryRepeats = queryRepeats + 1
        #     startDateFrom = startDateTo - datetime.timedelta(30)
        # elif (queryRepeats == 4):  # need to include (4*90) obvious and 6 days for a year
        #     queryRepeats = 5
        tic = time.perf_counter()
        for i in range(int(noOfMonths * 2)):
            inputObj["StartTimeTo"] = startDateTo
            inputObj["StartTimeFrom"] = startDateFrom
            inputObj["paginationInput"]["pageNumber"] = 1
            logger.debug(f"iteration number {i}")
            logger.debug(
                f"sad{inputObj['StartTimeTo']} and {inputObj['StartTimeFrom']}"
            )
            response = api.execute('findItemsAdvanced', inputObj)
            #print(response)
            response = response.dict()
            #print(inputObj)

            if response.get("searchResult") is None:
                logger.debug(f"no result at i {i}")
                break
            elif response.get("searchResult").get("item") is None:
                logger.debug(f"no result:at {i}")
                break
            #print(response["searchResult"])
            currentItems = response["searchResult"]["item"]
            items.extend(currentItems)
            # print("lenght of items , ", len(items))
            # print("page number is ", response["PageNumber"])
            # print("remaining pages", response["PaginationResult"])
            # print("has more number ", response["HasMoreItems"])
            remainingPages = int(
                response["paginationOutput"]["totalPages"]) - int(
                    response["paginationOutput"]["pageNumber"])

            if remainingPages == 0:
                break
            logger.debug(f"remaining pages: {remainingPages}")
            # query allows only upto max 100 pages
            remainingPages = min(99, remainingPages)
            multiThreadInputObjects = [
                copy.deepcopy(inputObj) for _ in range(remainingPages)
            ]
            for i in range(remainingPages):
                multiThreadInputObjects[i]["paginationInput"][
                    "pageNumber"] = i + 2
            #logger.debug(multiThreadInputObjects)
            with concurrent.futures.ThreadPoolExecutor(
                    max_workers=max(5, remainingPages / 20)) as executor:
                searchResults = []
                searchResults = executor.map(__retrieveFromSecondPage,
                                             multiThreadInputObjects)
                logger.debug("underr multithread")
                for searchResult in searchResults:

                    items.extend(searchResult["searchResult"]["item"])
                executor.shutdown()

            startDateFrom = startDateFrom - datetime.timedelta(15)
            startDateTo = startDateTo - datetime.timedelta(15)

        for item in items:
            # print("start time and ",item['listingInfo']['startTime']," end time; ", item['listingInfo']['endTime'])
            startTime = datetime.datetime.strptime(
                item['listingInfo']['startTime'], "%Y-%m-%dT%H:%M:%S.%fZ")
            endTime = datetime.datetime.strptime(
                item['listingInfo']['endTime'], "%Y-%m-%dT%H:%M:%S.%fZ")
            #item['DurationCalc']= (endTime.__sub__(startTime)).days
            item['DurationCalc'] = (endTime.__sub__(startTime)).days
        toc = time.perf_counter()
        logger.debug(f"search took {toc-tic} time with items: {len(items)}")
        logger.debug("now adding details like hit count and quantity sold")
        items = __getGood(items)

        __updateToGSheet(items, None, sellerIdFromSheet, noOfMonths)
        logger.debug("completed")
예제 #12
0
#!/usr/bin/python

#
# test finding api and write output to file
#
#

import os
from ebaysdk.finding import Connection as Finding
from ebaysdk.exception import ConnectionError

try:

    api = Finding(config_file='../config/ebay.yaml')

    api_dictionary = {
        'keywords':
        'Python',
        'itemFilter': [
            {
                'name': 'Condition',
                'value': 'Used'
            },
            {
                'name': 'MinPrice',
                'value': '200',
                'paramName': 'Currency',
                'paramValue': 'USD'
            },
            {
                'name': 'MaxPrice',
예제 #13
0
import json
from ebaysdk.finding import Connection as Finding

keywords = ['Car']
postalCode = ['95101']
api = Finding(domain='svcs.sandbox.ebay.com',
              appid="Shashwat-spendsma-SBX-e99eeec0d-a6b019b8",
              config_file=None)
response = api.execute(
    'findItemsAdvanced', {
        'keywords': 'Car',
        'sortOrder': 'PricePlusShippingLowest',
        'buyerPostalCode': postalCode
    })

print(json.dumps(response.dict(), indent=4))
예제 #14
0
def find(verb, api_request, product_id):
    try:
        api = Finding(debug=False,
                      domain='svcs.ebay.com',
                      siteid='EBAY-GB',
                      config_file='ebay.yaml')
        response = api.execute(verb, api_request)
        # pprint(response.dict())
        results = AsJson(response.dict())
        page = int(results.get_string('paginationOutput.pageNumber'))
        pages = int(results.get_string('paginationOutput.totalPages'))
        items = results.get_string('searchResult.item')

        while page < pages and page < 4:
            api_request['paginationInput']['pageNumber'] = page + 1
            response = api.execute(verb, api_request)
            # pprint(response.dict())
            results = AsJson(response.dict())
            page = int(results.get_string('paginationOutput.pageNumber'))
            items.extend(results.get_string('searchResult.item'))

        if not product_id:
            # Find the most common product_id
            products = Counter()
            for item in items:
                products[AsJson(item).get_string('productId.value')] += 1
            else:
                if len(products) > 1:
                    # remove the null id counts
                    products.pop('', None)
                    # get id from [(<id>, <count>)]
                    product_id = products.most_common(1)[0][0]

        for item in items:
            ending_date = AsJson(item).get_string('listingInfo.endTime')[:10]
            day = datetime.datetime.strptime(ending_date,
                                             '%Y-%m-%d').strftime('%A')
            amount = float(
                AsJson(item).get_string('sellingStatus.currentPrice.value',
                                        '999'))
            shipping = float(
                AsJson(item).get_string(
                    'shippingInfo.shippingServiceCost.value', '0'))

            item_id = AsJson(item).get_string('itemId', )
            url = AsJson(item).get_string('viewItemURL')
            total = '£{:03.2f} + £{:03.2f}'.format(amount, shipping)
            if AsJson(item).get_string('productId.value') == product_id:
                listing = '*{:<17} {} {} {} {}'.format(total, ending_date, day,
                                                       item_id, url)
            else:
                listing = ' {:<17} {} {} {} {}'.format(total, ending_date, day,
                                                       item_id, url)
            print(listing)
        else:
            print()

    except ConnectionError as e:
        print(e)
        print(e.response.dict())

    return product_id
예제 #15
0
def search_ebay(item):

    api = Finding(appid=APP_ID, config_file=None)
    response = api.execute('findItemsAdvanced', {'keywords': item})

    return response.dict()
예제 #16
0
파일: ebay.py 프로젝트: kkappel/pysnippets
#!/usr/bin/python
#
# (c) 2014 by Klaus Kappel

from ebaysdk.finding import Connection as Finding
api = Finding(domain='svcs.sandbox.ebay.com',
              appid="NovaLisa-352a-4d18-bade-3037954d9078")
response = api.execute('findItemsAdvanced', {'keywords': 'Nikon'})
print(response.dict())
def get_completed_findings_data(args, username, password, dbname, tablename):
    f = open('appId.txt')
    appId = f.read()
    connection_to_db = connect_to_database(username, password, dbname)
    cursor = connection_to_db.cursor()

    current_time = datetime.datetime.now()

    try:
        f = open('lasttime.txt', 'r')
        lines = f.readlines()
        start_time = lines[1]
        begin_time = lines[0]
        begin_time = begin_time.split("\n")[0]
        begin_time_datetime = datetime.datetime.strptime(
            begin_time, '%Y-%m-%d %H:%M:%S')
        print("Starting from time : {}".format(start_time))
    except:
        begin_time_datetime = datetime.datetime.now() - datetime.timedelta(
            seconds=1)
        start_time = datetime.datetime.now(
            pytz.timezone('Etc/GMT-0')) - datetime.timedelta(
                seconds=1)  ##ebay time is GMT time
        start_time = start_time.strftime('%Y-%m-%dT%H:%M:%S')
    if (current_time > begin_time_datetime):
        print("Starting Programme")
        try:
            api = Finding(config_file=None, siteid='EBAY-GB', appid=appId)

            api_requests = {
                'keywords':
                u'iPhone 7',
                'categoryId':
                9355,
                'itemFilter': [
                    {
                        'name': 'HideDuplicateItems',
                        'value': 'true'
                    },
                    {
                        'name': 'EndTimeTo',
                        'value': start_time
                    },
                ],
                'paginationInput': {
                    'entriesPerPage': 100,
                    'pageNumber': 1
                },
                'outputSelector': [
                    'SellerInfo', 'UnitPriceInfo', 'StoreInfo',
                    'PictureURLLarge', 'AspectHistogram'
                ],
                'sortOrder':
                'EndTimeSoonest'
            }

            response = api.execute('findCompletedItems', api_requests)
            number_of_pages = int(
                response.dict()['paginationOutput']['totalPages'])
            print(
                "There is a total of {} pages, if pages > 100 then more than one call is needed!"
                .format(number_of_pages))
            if (
                    number_of_pages > 100
            ):  ##ebay api only allows to search for max of 10,000 items, 100 items per page
                max_num_of_pages = 100
            else:
                max_num_of_pages = number_of_pages
            print("There is a total of : {} Pages".format(max_num_of_pages))
            print("Starting to pull information from all {} Pages".format(
                max_num_of_pages))

            for page in range(max_num_of_pages):
                api_requests = {
                    'keywords':
                    u'iPhone 7',
                    'categoryId':
                    9355,
                    'itemFilter': [
                        {
                            'name': 'HideDuplicateItems',
                            'value': 'true'
                        },
                        {
                            'name': 'EndTimeTo',
                            'value': start_time
                        },
                    ],
                    'paginationInput': {
                        'entriesPerPage': 100,
                        'pageNumber': page + 1
                    },
                    'outputSelector': [
                        'SellerInfo', 'UnitPriceInfo', 'StoreInfo',
                        'PictureURLLarge', 'AspectHistogram'
                    ],
                    'sortOrder':
                    'EndTimeSoonest'
                }

                response = api.execute('findCompletedItems', api_requests)
                item_results = response.dict()['searchResult']

                print(
                    "Inserting Page : {} Out of : {} Into Table : {} In Database : {}"
                    .format(page, max_num_of_pages, tablename, dbname))

                print("There are {} items on page {}".format(
                    len(item_results['item']), page))

                for item in item_results['item']:
                    item_flattened = item_to_flat_dictionary(item)
                    insert_value_into_db(connection_to_db, cursor,
                                         item_flattened, tablename)

                if (page == 99):
                    now = datetime.datetime.now() + datetime.timedelta(days=1)
                    now = now.strftime('%Y-%m-%d %H:%M:%S')
                    last_time = item_results['item'][-1]['listingInfo'][
                        'endTime']
                    last_time = last_time.split('.')[0]
                    last_time = datetime.datetime.strptime(
                        last_time, '%Y-%m-%dT%H:%M:%S')
                    last_time = last_time - datetime.timedelta(seconds=1)
                    last_time = last_time.strftime('%Y-%m-%dT%H:%M:%S')
                    pages_left = number_of_pages - max_num_of_pages
                    print(
                        """You've reached the 10,000, per 24 hours, call limit! 
                    You still have roughly {} pages left to pull
                    Start the program again at {},
                    The timestamp of the last item has been saved to a file and will automatically be called the next time you run this program!
                    """.format(pages_left, now))
                    export = open("lasttime.txt", 'w')
                    export.write('{}\n{}'.format(now, last_time))
                    export.close()

            cursor.close()
            connection_to_db.close()

        except ConnectionError as e:
            print("There has been a connection error")
            print(e)
            print(e.response.dict())

    else:
        print(
            "Your 24 Hour call period has not expired please run the program at {}"
            .format(begin_time_datetime))
예제 #18
0
	def __init__( self, **kwargs ):
		self.api = Finding( **kwargs )
예제 #19
0
    parser.add_option("-d", "--debug",
                      action="store_true", dest="debug", default=False,
                      help="Enabled debugging [default: %default]")
    parser.add_option("-y", "--yaml",
                      dest="yaml", default='ebay.yaml',
                      help="Specifies the name of the YAML defaults file. [default: %default]")
    parser.add_option("-a", "--appid",
                      dest="appid", default=None,
                      help="Specifies the eBay application id to use.")
    (opts, args) = parser.parse_args()
    return opts, args

(opts, args) = init_options()

## Defines api using finditemsadvanced
api = Finding(appid=opts.appid)

## Defines parser for xml and creates root object of xml string
parser = etree.XMLParser(recover=True, remove_blank_text=True)
def bareTag(tag):  #removes tag URL string
    lst = tag.split('}')
    return lst[-1]
namespace='{http://www.ebay.com/marketplace/search/v1/services}'
header = []   # init -- future column names
d = {}        # init -- values of the elements
item_ids=[]

## Creates csv for listing specific info
f_fname_tmp = 'f_temporary.csv'
with open(f_fname_tmp, 'wb') as fout:
    writer = csv.writer(fout)
예제 #20
0
#source: timotheus package
#https://github.com/timotheus/ebaysdk-python/wiki/Finding-API-class

from ebaysdk.finding import Connection as Finding
from ebaysdk.exception import ConnectionError

try:
    api = Finding(appid="IvyZhang-LEGGO-PRD-1bcdef08f-c0149495",
                  config_file=None)

    def lookup_item(product):
        '''
        
        product: string of product name. not case sensitive. 
        return offering: a list of dictionary, in order of best keyword match.

        '''
        # print(response.dict())
        # print(item_dict)
        response = api.execute('findItemsAdvanced', {'keywords': product})
        item_dict = response.dict()
        offerings = []
        for item in (item_dict['searchResult']['item']):
            title = item['title']
            price = item['sellingStatus']['convertedCurrentPrice']['value']
            url = item['viewItemURL']
            condition = item['condition']['conditionDisplayName']
            shipping = item['shippingInfo']['shippingType']
            item_info = {
                'title': title,
                'price': price,
예제 #21
0
def main():

    api = Finding(config_file=None,
                  domain='svcs.ebay.com',
                  appid="SatyaPra-MyEBPrac-PRD-abce464fb-dd2ae5fe",
                  devid="6c042b69-e90f-4897-9045-060858248665",
                  certid="PRD-bce464fbd03b-273a-4416-a299-7d41")

    items = list()
    inputObj = {
        "itemFilter": {
            "name": "Seller",
            "value": ""
        },
        "OutputSelector": [
            "Title", "itemId", "ViewItemURL", "SellingStatus",
            "ListingDuration", "listingInfo"
            "StartTime", "EndTime", "WatchCount", "ItemsPerPage",
            "PrimaryCategory", "HasMoreItems", "PageNumber",
            "ReturnedItemCountActual", "PaginationResult"
        ],
        "StartTimeFrom":
        "",
        "StartTimeTo":
        "",
        "IncludeWatchCount":
        "true",
        "paginationInput": {
            "entriesPerPage": "100",
            "pageNumber": "1"
        }
    }

    startDateTo = datetime.datetime.now()
    startDateFrom = startDateTo - datetime.timedelta(90)
    sellerIdFromSheet, noOfMonths = getFromSheet()
    print("seller id fro sheet ",
          (sellerIdFromSheet if sellerIdFromSheet is not None else "None"))
    print("no of months ", noOfMonths)
    if sellerIdFromSheet is not None and len(sellerIdFromSheet) > 0:

        inputObj["itemFilter"]["value"] = sellerIdFromSheet
        queryRepeats = int(noOfMonths / 3)
        if (noOfMonths == 1):  #one month only
            queryRepeats = queryRepeats + 1
            startDateFrom = startDateTo - datetime.timedelta(30)
        elif (queryRepeats == 4
              ):  #need to include (4*90) obvious and 6 days for a year
            queryRepeats = 5

        for i in range(queryRepeats):
            inputObj["StartTimeTo"] = startDateTo
            inputObj["StartTimeFrom"] = startDateFrom
            inputObj["paginationInput"]["pageNumber"] = 1
            print("iteration number ", i)
            print(inputObj["StartTimeTo"], "  ", inputObj["StartTimeFrom"])
            if True:

                response = api.execute('findItemsAdvanced', inputObj).dict()
                #print(response)
                if response["searchResult"] is None:
                    print("no result at i ", i)
                    break
                currentItems = response["searchResult"]["item"]
                items.extend(currentItems)
                #print("lenght of items , ", len(items))
                #print("page number is ", response["PageNumber"])
                #print("remaining pages", response["PaginationResult"])
                #print("has more number ", response["HasMoreItems"])
                remainingPages = int(
                    response["paginationOutput"]["totalPages"]) - int(
                        response["paginationOutput"]["pageNumber"])

                if remainingPages == 0:
                    break
                inputObj["paginationInput"]["pageNumber"] = int(
                    response["paginationOutput"]["pageNumber"]) + 1
            if i == 3:
                startDateFrom = startDateFrom - datetime.timedelta(
                    6)  # just for last 6 days in 365/366  days
            else:
                startDateFrom = startDateFrom - datetime.timedelta(90)
            startDateTo = startDateTo - datetime.timedelta(90)

        #print(items, file=open("1.txt", "w"))
        print("total items: ", len(items))
        updateQuantitySoldEtc1(items)
        print("now adding details like hit count and quantity sold")
예제 #22
0
import datetime

try:
    from ebaysdk.finding import Connection as Finding
except:
    import pip
    pip.main(['install', '--user', 'ebaysdk'])
    from ebaysdk.finding import Connection

try:
    api = Finding(appid=appid, config_file=None)

    response = api.execute('findItemsByProduct', {
        'productId.type': 'ReferenceID',
        'productID.value': '311341714658'
    })
    print(response.dict())
except ConnectionError as e:
    print(e)
    print(e.response.dict())
예제 #23
0
from ebaysdk.finding import Connection as Finding
import json

#"REDACTED" AppID

try:
    api = Finding(config_file='ebay.yaml')
    response = api.execute('findItemsAdvanced', {
        'keywords': 'Doom'
    })  #works. But needed the YAML file in my Home directory. Don't know why
    """
        with open("ebayResults", "w") as f:   
        json.dump(response.dict(), f)
    """
    #makes a HUGE EFFING dicitonary with nested dictionaries and list. Need to be a better way
    print(response.dict()["searchResult"]["item"])

    lowest_price = 100

    #print(response.dict()) #yields a CRAP ton of results
except ConnectionError as e:
    print(e)
    print(e.response.dict())
예제 #24
0
def finding(*args, **kwargs):
    from ebaysdk.finding import Connection as Finding
    return Finding(*args, **kwargs)