Home > database >  Click on every element in the catalog with Python selenium
Click on every element in the catalog with Python selenium

Time:04-11

I only started to study python. I have a problem with my code. I use Python selenium and I don’t understand how I can click on the first element in this code, then go to products__item, after that return back to catalog and click on the second element, then on the third element using selenium.

This is code from a typical internet shop. I understand I need to use a cycle “for” for it but how to do it I don’t know.

<div  style="position: relative">
    <div >
    <a href="/catalog/dveri-mezhkomnatnyye/dveri-ekoshpon/bravo/bravo-21-snow-art" >
    <div > Product-1 </div>
    <div > Snow Art </div>
    <div > <div > <img src="/storage/products/small/60fa84e2b06096.72907873.jpg"> </div>
    <div > </div>

    <div >
    <a href="/catalog/dveri-mezhkomnatnyye/dveri-ekoshpon/bravo/bravo-21-snow" >
    <div > Product-2 </div>
    <div > Snow </div>
    <div > <div > <img src="/storage/products/small/60fa84e2b06096.72907874.jpg"> </div>
    <div > </div>

    <div >
    <a href="/catalog/dveri-mezhkomnatnyye/dveri-ekoshpon/bravo/bravo-21-snow-art-classic" >
    <div > Product-3 </div>
    <div > Snow Art Classic </div>
    <div > <div > <img src="/storage/products/small/60fa84e2b06096.72907875.jpg"> </div>
    <div > </div>

CodePudding user response:

Hope it helps!

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

driver = webdriver.Chrome('path/to/chromedriver')

driver.get("https://dveri.com/catalog/dveri-mezhkomnatnyye?page=1")

wait = WebDriverWait(driver, 10)

elements_xpath = '//div[@]/a[@]'
# Wait for emelents to load
wait.until(EC.element_to_be_clickable((By.XPATH, elements_xpath)))

num_elements = len(driver.find_elements(By.XPATH, elements_xpath))
ac = ActionChains(driver)

for i in range(num_elements):
    # Wait until elements are clickable
    wait.until(EC.element_to_be_clickable((By.XPATH, elements_xpath)))
    # Get all elements and select only the i-th one
    element = driver.find_elements(By.XPATH, elements_xpath)[i]
    # Click the element with the offset from center to actually go to the other page
    ac.move_to_element(element).move_by_offset(0, 100).click().perform()

    # Here do whatever has to be done on a specific webpage

    time.sleep(1)
    # Go back to the previous page
    driver.execute_script("window.history.go(-1)")
  • Related