selenium with python 如何获得该类别中是否有产品的结果

selenium with python how to get the result that products available in this category or not

我是自动化新手,我想获取可用或不可用的儿童类别中的产品数量,但我无法获取。请帮我解决这个问题。 我的代码在这里:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver import ActionChains
from time import sleep
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import ElementNotVisibleException


driver = webdriver.Chrome(executable_path='C:\Program Files\JetBrains\PyCharm 2021.1.1/chromedriver.exe')

# Windows Maximize
driver.maximize_window()
# opening website URL
driver.get("http://esindbaad.com/")
# checking catagories one bye one
# Food & Grocery (Beverages)
food = driver.find_element_by_xpath("//*[@id='head-wrapper']/div/div/div/div/ul/li[1]/a")
Beverages = driver.find_element_by_xpath("//*[@id='head-wrapper']/div/div/div/div/ul/li[1]/div/div/div/div/div/div[1]/div[1]/div/ul/li/a")
actions = ActionChains(driver)
actions.move_to_element(food).move_to_element(Beverages).click().perform()
driver.execute_script("window.scroll(0,900)")
# Return back to home page
driver.implicitly_wait(5)
driver.execute_script ( "window.history.go(-1)" )
# Food & Grocery (fruits)
food = driver.find_element_by_xpath("//*[@id='head-wrapper']/div/div/div/div/ul/li[1]/a")
fruits = driver.find_element_by_xpath("//*[@id='head-wrapper']/div/div/div/div/ul/li[1]/div/div/div/div/div/div[2]/div[1]/div/ul/li/a")
actions = ActionChains(driver)
actions.move_to_element(food).move_to_element(fruits).click().perform()
driver.execute_script("window.scroll(0,900)")
# Return back to home page
driver.implicitly_wait(5)
driver.execute_script ( "window.history.go(-1)" )

在此我想得到食品和杂货(饮料)以及其他领域有多少产品可用的结果。

要获取一页上的产品数量,您应该获取产品列表并测量其长度。

这里: 1 我去主页 2 单击食品和杂货 3.使用唯一定位器获取产品编号:

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


driver = webdriver.Chrome(executable_path='/snap/bin/chromium.chromedriver')
driver.implicitly_wait(15)
driver.get('https://esindbaad.com/')
driver.find_element_by_css_selector(".item-vertical.with-sub-menu.hover>a[href*='cat1_id=5&cat2_id=0&cat3_id=0']").click()  # clicking the food & grocery category
wait = WebDriverWait(driver, 30)
wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, ".products-list>.product-layout")))
cards = driver.find_elements_by_css_selector(".products-list>.product-layout")
length = len(cards)
print(length)
driver.quit()

得到输出:15。 您问题的主要解决方案是这两行:

cards = driver.find_elements_by_css_selector(".products-list>.product-layout")
length = len(cards)

find_elements_by_css_selector 用于查找元素列表。 除此之外,您不必多次设置相同的隐式等待。仅在开始时设置它,它将被应用。

您的代码还有其他问题,但我从中抽象出来(定位器、windows 处理等)。