selenium Python:程序中的第二个循环没有执行

6jygbczu  于 2023-02-12  发布在  Python
关注(0)|答案(2)|浏览(235)

我的代码不工作时到达第二个循环.当我悬停在第一个类别它显示第二个类别,我需要悬停在第二个类别看到第三个类别.这里是我的代码:

driver.get("https://www.daraz.com.bd/")
main_category = driver.find_elements(By.CSS_SELECTOR , '.lzd-site-menu-root-item span')
for i in main_category:
    hover = ActionChains(driver).move_to_element(i)
    hover.perform()
    time.sleep(1) 
    sub_category_one = driver.find_elements(By.CSS_SELECTOR , ".Level_1_Category_No1 [data-spm-anchor-id] span")
    for i in sub_category_one:
             hover = ActionChains(driver).move_to_element(i)
             hover.perform()
uplii1fm

uplii1fm1#

要对第一个类别执行Mouse Hover(显示第二个类别),然后对第二个类别执行Hover(查看第三个类别),您需要引入WebDriver等待visibility_of_all_elements_located(),您可以使用以下locator strategies

  • 代码块:
driver.get('https://www.daraz.com.bd/')
main_category = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, ".lzd-site-menu-root-item span")))
for i in main_category:
    ActionChains(driver).move_to_element(i).perform()
    time.sleep(1) 
    sub_category_one = WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "ul.Level_1_Category_No1 li.lzd-site-menu-sub-item")))
    for j in sub_category_one:
        ActionChains(driver).move_to_element(j).perform()
      • 注意**:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
vh0rcniy

vh0rcniy2#

首先要抓取站点,bs4和迭代列表似乎是一个更好的方法。
现在find_elements返回了一个列表,在第二个for循环中,您正在迭代一个只有一个值的列表,当我检查页面时,我注意到一个活动的子菜单或子子菜单被赋以lzd-site-menu-sub-activelzd-site-menu-grand-active类。

main_category = driver.find_elements(By.CSS_SELECTOR, ".lzd-site-menu-root-item span")
for main in main_category:
    ActionChains(driver).move_to_element(main).perform()

    sub_category = WebDriverWait(driver, 3).until(
        lambda x: x.find_elements(By.CSS_SELECTOR, ".lzd-site-menu-sub-item span")
    )
    for sub in sub_category:
        ActionChains(driver).move_to_element(sub).perform()

        subsub_category = WebDriverWait(driver, 3).until(
            lambda x: x.find_elements(By.CSS_SELECTOR, ".lzd-site-menu-grand-item span")
        )

        for subsub in subsub_category:
            ActionChains(driver).move_to_element(subsub).perform()

这段代码成功地在第三层上悬停,正如你将看到的。然而,由于糟糕的CSS_Selector,它有点无用。我希望这能有所帮助。

相关问题