簡體   English   中英

PYTHON:Selenium 循環 selenium.common.exceptions.TimeoutException

[英]PYTHON : Selenium loop selenium.common.exceptions.TimeoutException

我正在嘗試從每個單獨的產品頁面中抓取產品詳細信息。 我嘗試在 xpath 之間為“元素”使用 append 和 integer。 對於j = 1 ,for i in range 循環運行沒有問題,打印getproductname但對於j = 2拋出錯誤。

你如何修復循環? 我無法弄清楚這里似乎是什么問題:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

CHROMEDRIVER_PATH = '/Users/reezalaq/PycharmProjects/wholesale/driver/chromedriver'
chrome_options = webdriver.ChromeOptions()
driver = webdriver.Chrome(CHROMEDRIVER_PATH, options=chrome_options)
chrome_options.accept_untrusted_certs = True
chrome_options.assume_untrusted_cert_issuer = True
chrome_options.headless = False

driver.get('https://www.skinnymixes.com/collections/skinny-syrups')
for i in range(1,20):
    j = str(i)
    print(j)
    elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, '#collection-content > div.collection-listing > div > div.row.product-list.text-center.mb-3.in-view.in-view--active.in-view--loaded > div:nth-child('+ j +') > a')))
    print(elements)
    for element in elements:
        url = element.get_attribute('href')
        print(url)
        #open new tab with specific url
        driver.execute_script("window.open('" +url +"');")
        #switch to new tab
        driver.switch_to.window(driver.window_handles[1])
        getproductname = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, '//*[@id="shopify-section-product"]/div/div[1]/div/div[2]/h1')))
        print(getproductname.text)
Traceback (most recent call last):
  File "/Users/reezalaq/PycharmProjects/legasimall/skinny/getproducts.py", line 70, in <module>
    elements = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, '#collection-content > div.collection-listing > div > div.row.product-list.text-center.mb-3.in-view.in-view--active.in-view--loaded > div:nth-child('+ j +') > a')))
  File "/Users/reezalaq/PycharmProjects/legasimall/venv/lib/python3.7/site-packages/selenium/webdriver/support/wait.py", line 80, in until
    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: 

你的代碼的問題是

  • 它在新的 window 中打開一個產品,將驅動程序切換到它,然后它會抓取信息

  • 但在那之后,它不會將驅動程序切換回原來的 window。

因此,基本上在循環結束時,您需要將其切換回原始 window,即

任何一個,

driver.switch_to.default_content()

或者,在切換到新的 window 之前保存原來的 window 句柄,並使用它將驅動程序切換回它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM