如何获得具有不同结尾的XPATH元素?



我试图添加每个产品到购物车通过点击产品,然后单击按钮将产品添加到购物车从这个网站https://www.bershka.com/ro/femeie/accesorii/%C8%99osete-c1010194004.html

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import time

options = Options()
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
options.add_argument("start-maximized")
webdriver_service = Service('C:webdriverschromedriver.exe')
driver = webdriver.Chrome(options=options, service=webdriver_service)
wait = WebDriverWait(driver, 30)
driver.get("https://www.bershka.com/ro/femeie/accesorii/%C8%99osete-c1010194004.html")

cookies_bttn = driver.find_element(By.ID, "onetrust-accept-btn-handler")
cookies_bttn.click()
driver.implicitly_wait(10)
country_save = driver.find_element(By.CSS_SELECTOR, "#geoblocking > div > div > div.select-country-container > button.button.is-sm.confirm")
country_save.click()
hoover = ActionChains(driver)
time.sleep(10)
pbody = wait.until(EC.presence_of_element_located((By.TAG_NAME, 'body')))
for x in range(5):
pbody.send_keys(Keys.PAGE_DOWN)
print('scrolled')
time.sleep(1)
sosete = wait.until(EC.presence_of_all_elements_located((By.XPATH, '//div[@class="category-product-card"]')))
print(len(sosete))

for x in str(len(sosete)):
ActionChains(driver).move_to_element(sosete).perform()
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".quick-purchase__detail__button"))).click()

输出:AttributeError: move_to需要一个WebElement

我尝试了很多方法,但每次都出现错误,我找不到任何解决方案我考虑过使用XPATH创建for循环,但我不知道如何获得每个产品,因为它们有不同的li,像这样:First product =/html/body/div[2]/div/div/div[2]/main/div/div/div/div/div/div[2]/section[1]/div/ul/li[1]/div第二个产品=/html/body/div[2]/div/div/div[2]/main/div/div/div/div/div[2]/section[1]/div/ul/li[2]/div等等

假设前面答案中的代码,设actions定义为:

actions = ActionChains(driver)

根据您的地理IP地址,您可能需要:

try:
wait.until(EC.element_to_be_clickable((By.XPATH, '//span[@class="bskico-cancel-16"]'))).click()
print('removed location popup')
except Exception as e:
print('no location popup')

假设项目列表如下:

items = wait.until(EC.presence_of_all_elements_located((By.XPATH, '//div[@class="category-product-card"]')))

你添加到你的代码:

for i in items:
actions.move_to_element(i).perform()
t.sleep(5)
i.find_element(By.XPATH, './/span[@class="quick-purchase__detail__button__text"]').click()
print('added to basket', i.text)
t.sleep(5)

硬编码的等待时间是用来解释网络慢速和服务器慢速的。购物篮最多可容纳26种商品,因此您无法将所有商品都添加到购物篮中。

最新更新