Я пытаюсь автоматизировать процесс, с помощью которого я могу посетить веб-сайт и получить подробную информацию о 100 самых популярных продуктах на этой странице и разместить его в файле Excel.
Объяснение кода:
У меня есть класс Webscraper внутри которого я вызываю две функции. Сначала я вызываю функцию scroll_and_click_view_more, которая просто прокручивает веб-страницу, которую я посещаю. Затем я вызываю функцию prod_vitals, которая извлекает код продукта и названия продуктов с этой веб-страницы.
Описание ошибки:
Всякий раз, когда я выполняю код ниже, до определенного максимального значения нет. продуктов, код зависает после точки и выдает ошибку «Индекс вне диапазона». Если я устанавливаю max_count_of_products=50, код зависает на строке. Если я устанавливаю
max_count_of_products=100, код зависает на 93. Не существует фиксированного индекса, где Я застреваю. Если я изменю значение max_count_of_products, точка, в которой код зависает, также изменится.
Я прилагаю скриншоты ошибки. ниже.
max_count_of_products=50
[img]https://i. sstatic.net/65ZocuYB.png[/img]
max_count_of_products=100
Код: Выделить всё
**Please find my code below with API method:**
Код: Выделить всё
def prod_vitals(title,url):
count_of_items=1
products_data = [] # Array to store all product data for our excel sheet
page = 0
list_price = 0 # Variable to store list price
sale_price = 0 # Variable to store sale price
discount1 = 0 # Variable to store discount% that is displayed on the site
discount2 = 0 # Variable to store discount% calculated manually
res = "Incorrect"
if '/shop' not in url:
print("Not in url",url)
return "No product tiles found"
try:
while True:
page = page + 1 #page result start from 2 and each page contains 16 result
ct = count_of_items + 15 #count to adjust loop as each page contains 16 results
if(page==1):
full_url = f"{url}"
else:
full_url = f"{url}?page={page}"
if 'api/get-shop' not in full_url:
full_url = full_url.replace('/shop', '/api/get-shop')
session = requests.Session()
response = session.get(full_url, headers=headers, verify=False)
products = response.json().get('pageData', {}).get('products', [])
#products = len(response.json()['pageData']['products'])
print(full_url,"\n", len(products),"\n")
if '/get-shop' in full_url and not products:
print("No product tiles found",full_url)
return "No product tiles found"
#print(response.json()['pageData']['products'],"\n")
for i in products:
print(i['defaultVariant']['prices'],"\n")
pro_code = i['defaultColor']['vgId']
#print(pro_code)
pro_name = i['name']
#print(pro_name)
pdpurl = i['defaultColor']['url']
#print(pdpurl,"\n")
sale_price = i['defaultVariant']['prices']['currentPrice'] if i['defaultVariant']['prices']['currentPrice'] else 0
list_price = i['defaultVariant']['prices']['regularPrice'] if 'regularPrice' in i['defaultVariant']['prices'] and i['defaultVariant']['prices']['regularPrice'] else 0
discount1 = i['defaultVariant']['prices']['discount'] if i['defaultVariant']['prices']['discount'] and i['defaultVariant']['prices']['discount'] is not None else 0
if list_price > 0 and sale_price > 0:
discount2 = round(((list_price - sale_price) / list_price) * 100)
res = "Correct" if discount1 == discount2 else "Incorrect"
elif(list_price ==0 and discount1 == 0):
discount2 = 0
res = "Correct"
translator = Translator()
translated_pro_name = translator.translate(pro_name, dest='en').text
if count_of_items max_count_of_products: #if ct > count thats mean we reach our goal so break the loop
break
except Exception as e:
print(e)
pass
Код: Выделить всё

Подробнее здесь: https://stackoverflow.com/questions/790 ... rom-a-webs