Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

237
Views
analizando URL usando selenio cuando xpath tiene una diferencia en la parte media

Estoy practicando web scraping usando Selenium y tratando de extraer todos los enlaces de productos de la página principal de Lululemon->Woman. Pero descubrí que cuando traté de usar XPath para ubicar las URL de los productos y luego recorrer las listas, la parte diferente de cada XPath para cada producto está en el medio, lo que sugiere que no puedo hacer lo que esperaba.

 For example, the Xpath of each product is : /html/body/div[1]/div/main/div/section/div/div[3]/div[2]/div[2]/div/div[133]/div/div/div[2]/h3/a /html/body/div[1]/div/main/div/section/div/div[3]/div[2]/div[2]/div/div[134]/div/div/div[2]/h3/a /html/body/div[1]/div/main/div/section/div/div[3]/div[2]/div[2]/div/div[1]/div/div/div[2]/h3/a See, the difference of each XPath lies in 133, 134, and 1, which represent the #id of products on this page

Entonces, ¿cómo puedo crear una lista completa de información de todos los productos (si XPath funciona) que me permita recorrerla para obtener la lista de cada producto? ¿Alguien puede ayudarme? Pegué mi código actual y adjunté la captura de pantalla como referencia. ¡Muchas gracias!

 #this is how I got the web page driver_path = 'D:/Python/Selenium/chromedriver' url = "https://shop.lululemon.com/c/womens-leggings/_/N-8s6" max_pass = 5 #get each product's url option1 = webdriver.ChromeOptions() option1.add_experimental_option('detach',True) driver = webdriver.Chrome(chrome_options=option1,executable_path=driver_path) driver.get(url) sleep(2) for i in range(max_pass): sleep(3) try: driver.find_element_by_xpath('/html/body/div[1]/div/main/div/section/div/div[4]/div/button/span').click() except: pass try: driver.find_element_by_xpath('/html/body/div[1]/div/main/div/section/div/div[2]/div/button/span').click() except: pass sleep(3) driver.execute_script("window.scrollTo(0,document.body.scrollHeight);") #the next step should be to find the pattern of where each URL is located (this should be a list), then I need to loop through the list to get "href" for every single product #By the way, I have also tried to use class name "link lll-font-weight-medium" to locate, but I don't know why python says "Message: chrome not reachable (Session info: chrome=95.0.4638.69)" [p.get_attribute('href') for p in driver.find_elements_by_class_name('link lll-font-weight-medium')] #this doesn't work

ingrese la descripción de la imagen aquí

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Para imprimir los atributos href , debe inducir WebDriverWait para la visibilidad_de_todos los elementos_ubicados() y puede usar cualquiera de las siguientes estrategias de localización :

  • Usando CSS_SELECTOR :

     driver.get("https://shop.lululemon.com/c/womens-leggings/_/N-8s6") print([my_elem.get_attribute("href") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "h3.product-tile__product-name > a")))])
  • Usando XPATH :

     driver.get("https://shop.lululemon.com/c/womens-leggings/_/N-8s6") print([my_elem.get_attribute("href") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//h3[contains(@class, 'product-tile__product-name')]/a")))])
  • Salida de la consola:

     ['https://shop.lululemon.com/p/womens-leggings/Invigorate-HR-Tight-25/_/prod9750552?color=52445', 'https://shop.lululemon.com/p/womens-leggings/Wunder-Train-HR-Tight-25/_/prod9750562?color=47184', 'https://shop.lululemon.com/p/womens-leggings/Instill-High-Rise-Tight-25/_/prod10641675?color=30210', 'https://shop.lululemon.com/p/womens-leggings/Base-Pace-High-Rise-Tight-25/_/prod10641591?color=51039', 'https://shop.lululemon.com/p/womens-leggings/Align-Crop-21-Shine/_/prod10850236?color=51756', 'https://shop.lululemon.com/p/women-pants/Fast-And-Free-Tight-II-NR/_/prod8960003?color=28948', 'https://shop.lululemon.com/p/women-pants/Align-Pant-Full-Length-28/_/prod8780551?color=46741', 'https://shop.lululemon.com/p/women-pants/Align-Pant-2/_/prod2020012?color=26950', 'https://shop.lululemon.com/p/women-pants/Align-Pant-Super-Hi-Rise-28/_/prod9200552?color=26083']
  • Nota : debe agregar las siguientes importaciones:

     from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
about 4 years ago · Juan Pablo Isaza Report

0

Al obtener todos los enlaces de los productos mostrados, puede ir con xpath pero, en mi opinión, los css selectors son más cómodos:

 for a in driver.find_elements(By.CSS_SELECTOR, '[data-testid="product-list"] h3 a'): print(a.get_attribute('href'))

En lugar de imprimir en la iteración, también puede agregarlos a una lista o procesar la página de un solo producto directamente.

Ejemplo (selenio 4)

 ... driver.get(url) last_height = driver.execute_script("return document.body.scrollHeight") while True: driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(0.5) new_height = driver.execute_script("return document.body.scrollHeight") if new_height == last_height: break last_height = new_height for a in driver.find_elements(By.CSS_SELECTOR, '[data-testid="product-list"] h3 a'): print(a.get_attribute('href'))
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!