Я не уверен, почему, но мой скрипт всегда прекращает сканирование, как только достигает стр. 9. Здесь нет ошибок, исключений или предупреждений, поэтому я немного растерялся.
Кто-нибудь может мне помочь?
P.S. Вот полный сценарий на тот случай, если кто-то захочет проверить его на себе!
def initiate_crawl():
def refresh_page(url):
ff = create_webdriver_instance()
ff.get(url)
ff.find_element(By.XPATH, '//*[@id="FilterItemView_sortOrder_dropdown"]/div/span[2]/span/span/span/span').click()
ff.find_element(By.XPATH, '//a[contains(text(), "Discount - High to Low")]').click()
items = WebDriverWait(ff, 15).until(
EC.visibility_of_all_elements_located((By.XPATH, '//div[contains(@id, "100_dealView_")]'))
)
print(len(items))
for count, item in enumerate(items):
slashed_price = item.find_elements(By.XPATH, './/span[contains(@class, "a-text-strike")]')
active_deals = item.find_elements(By.XPATH, './/*[contains(text(), "Add to Cart")]')
if len(slashed_price) > 0 and len(active_deals) > 0:
product_title = item.find_element(By.ID, 'dealTitle').text
if product_title not in already_scraped_product_titles:
already_scraped_product_titles.append(product_title)
url = ff.current_url
ff.quit()
refresh_page(url)
break
if count+1 is len(items):
try:
next_button = WebDriverWait(ff, 15).until(
EC.text_to_be_present_in_element((By.PARTIAL_LINK_TEXT, 'Next→'), 'Next→')
)
ff.find_element(By.PARTIAL_LINK_TEXT, 'Next→').click()
url = ff.current_url
ff.quit()
refresh_page(url)
except Exception as error:
print(error)
ff.quit()
refresh_page('https://www.amazon.ca/gp/goldbox/ref=gbps_ftr_s-3_4bc8_dct_10-?gb_f_c2xvdC0z=sortOrder:BY_SCORE,discountRanges:10-25%252C25-50%252C50-70%252C70-&pf_rd_p=f5836aee-0969-4c39-9720-4f0cacf64bc8&pf_rd_s=slot-3&pf_rd_t=701&pf_rd_i=gb_main&pf_rd_m=A3DWYIK6Y9EEQB&pf_rd_r=CQ7KBNXT36G95190QJB1&ie=UTF8')
initiate_crawl()
Печать длины items
тоже вызывает странное поведение. Вместо того, чтобы всегда возвращать 32, что соответствовало бы количеству элементов на каждой странице, он печатает 32
для первой страницы, 64
для второй, 96
для третьей и т. Д. И т. Д. Я исправил это, используя //div[contains(@id, "100_dealView_")]/div[contains(@class, "dealContainer")]
вместо //div[contains(@id, "100_dealView_")]
в качестве XPath для переменной items
. Я надеюсь, что это причина, по которой возникают проблемы на странице 9. Я провожу тесты прямо сейчас. Обновление. Сейчас выполняется парсинг страницы 10 и более поздних, поэтому проблема решена.
time.sleep(n)
и провожу тест с этим. после этого напечатаю длину! спасибо за вклад ‹3 - person oldboy   schedule 07.10.2018items
не сможет ничего найти. я имею в виду, это должно или выдать ошибку. Тем не менее, стоит изучить этот пункт - person oldboy   schedule 07.10.2018len(items)
, возвращающего количество элементов на каждой странице, он возвращает32
для первой страницы, затем64
для второй страницы (33-64),96
для третьей ( 65-96) и так далее ... как такое может происходить ?? с - person oldboy   schedule 08.10.2018quit
экземпляр webdriver, а затем создаю другой экземпляр заново ... человек протестировал гораздо более длинные скрипты на Amazon, и похоже, что они сделали почти все, что в их силах, чтобы попробовать и не допускать соскабливания / дозирования материала. несчастный - person oldboy   schedule 08.10.2018if count+1...
на том же уровне, что и операторif product_title not in
, и получил следующую ошибку:HTTPConnectionPool(host='127.0.0.1', port=58992): Max retries exceeded with url: /session/e8beed9b-4faa-4e91-a659-56761cb604d7/element (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000022D31378A58>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))
, что странно, поскольку я никогда не получал [продолжение] - person oldboy   schedule 08.10.2018if
вызовет это - person oldboy   schedule 08.10.2018