【发布时间】:2019-03-12 12:37:00
【问题描述】:
我不知道为什么,但我的脚本在到达page 9 时总是停止爬行。没有错误、异常或警告,所以我有点不知所措。
有人可以帮帮我吗?
附: Here is the full script in case anybody wants to test it for themselves!
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_")] 作为items 变量的XPath 解决了这个问题。我希望这就是它在第 9 页遇到问题的原因。我现在正在运行测试。 更新:现在正在抓取第 10 页及以后,因此问题已解决。
【问题讨论】:
-
你监控爬取过程了吗?第9页还有“更多”之类的按钮吗?
-
@jihan1008 一切都受到监控。我检查了 xpath,一切,似乎没有任何问题
-
你能检查不同的浏览器版本吗
-
我无法让你的脚本运行,但似乎在某些时候你得到了长度为 0 的项目,因此枚举循环没有发生。尝试在循环之前打印项目的长度,看看在代码结束之前会发生什么。
-
@AndrewMcDowell 好主意!我在 pt,我相信它一定在剧本的其他地方。我目前设置了一堆
time.sleep(n)s 并用它进行测试。之后我会打印长度!感谢您的输入
标签: python selenium python-requests geckodriver urllib3