你能帮我用Selenium点击添加到购物车按钮吗?



我正在尝试做一个教程,学习python中的Selenium,但我似乎无法让Selenium单击"添加到Cart"按钮,使用find_element_by_class或find_element_by_XPATH。问题是检查该项目是否缺货,如果缺货,则刷新网页并重新启动脚本。如果商品有货,则应点击"添加到目录">

我正在使用:

Python v3.9

Chrome v87

这是我正在练习的URL:

https://www.currys.co.uk/gbuk/tv -和-家- entertainment/televisions/televisions/samsung ue75tu7020kxxu - 75智能- 4 k - ultra - hd - hdr - led电视- 10213562 - pdt.html

这是我当前的点击代码:

# Selenium Tutorial #1
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
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
import time
driver = webdriver.Chrome(r"C:UsersSte1337Desktopchromedriverchromedriver.exe")
driver.get("https://www.currys.co.uk/gbuk/tv-and-home-entertainment/televisions/televisions/samsung-ue75tu7020kxxu-75-smart-4k-ultra-hd-hdr-led-tv-10213562-pdt.html")
#search = driver.find_element_by_id(ContentPlaceHolder1_NotifyBtn)
link = driver.find_element_by_id("onetrust-accept-btn-handler")
link.click
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "onetrust-accept-btn-handler"))
)
element.click()
except Exception:
pass
driver.implicitly_wait(2)
try:
element = WebDriverWait(driver, 1).until(
EC.presence_of_element_located((By.XPATH, "email-desktop"))
)
time.sleep(1)
browser.refresh()
except:
driver.find_element_by_class_name("Button__StyledButton-bvTPUF hZIOeU Button-jyKNMA GZkwS")
link.click()

不能将多个类传递给find_element_by_class_name。请使用driver.find_element_by_css_selectorxpath

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
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
import time
driver = webdriver.Chrome(r"C:UsersFrankDocumentsPython Scriptschromedriver_win32chromedriver.exe")
driver.get("https://www.currys.co.uk/gbuk/tv-and-home-entertainment/televisions/televisions/samsung-ue75tu7020kxxu-75-smart-4k-ultra-hd-hdr-led-tv-10213562-pdt.html")
#search = driver.find_element_by_id(ContentPlaceHolder1_NotifyBtn)
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "onetrust-accept-btn-handler"))
)
element.click()
except Exception:
pass
driver.implicitly_wait(2)
try:
element = WebDriverWait(driver, 1).until(
EC.presence_of_element_located((By.XPATH, "email-desktop"))
)
time.sleep(5)
driver.refresh()
except:
button = driver.find_element_by_css_selector("button.Button__StyledButton-bvTPUF.hZIOeU.Button-jyKNMA.GZkwS")

接下来,如果您调用button.is_displayed(),它将返回False,因为它是一个隐藏元素。这意味着您不能使用button.click()与它交互。相反,你可以使用javascript来点击按钮。

driver.execute_script("arguments[0].click();", button)

相关内容

  • 没有找到相关文章

最新更新