gpt4 book ai didi

python - 如何使用selenium python单击 headless (headless)按钮并且按钮内部有div标签?

转载 作者:行者123 更新时间:2023-12-01 00:14:21 26 4
gpt4 key购买 nike

使用此代码无需 headless (headless)方法..网站链接:https://www.na-kd.com/en/sweaters?sortBy=popularity&count=108

try:
element = self.driver.find_element_by_xpath('//*[@id="container"]/div/div/div[3]/div/div[4]/div/div[1]/div[2]/div[1]/button')
self.driver.execute_script("arguments[0].click();", element)

except Exception as e:
print('Error in clicking BTN : '+str(e))

因为这个 btn 内部有 div 标签,所以它不能与 headless (headless)和虚拟显示一起使用。

我也尝试等待:

    try:
element=WebDriverWait(self.driver, 20).until(
EC.element_to_be_clickable((By.XPATH, '//*[@id="container"]/div/div/div[3]/div/div[4]/div/div[1]/div[2]/div[1]/button')))
self.driver.execute_script("arguments[0].click();", element)

except Exception as e:
print('Error in clicking BTN : '+str(e))

chromedriver --version
ChromeDriver 78.0.3904.70
Google Chrome 78.0.3904.108

最佳答案

在触发任何事件时使用 headless (headless)模式添加 window-size() 因为 headless (headless)浏览器无法识别在没有窗口大小的情况下单击的位置。

点击加载更多产品按钮引发WebDriverWait()并等待element_to_be_clickable()并使用下面的xpath

要验证按钮是否被单击,只需向下滚动页面并从 div 标签获取值即可。

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

# Headless option with window-size()
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('window-size=1920x1080');

driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("https://www.na-kd.com/en/sweaters?sortBy=popularity&count=108&ssr=on&loadfailure=1")

# Load more products button

element=WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//button[.//div[text()='Load more products']]")))
driver.execute_script("arguments[0].click();", element)

# To verify that whether button is clicked or not
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(2) #wait for page to load
print(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='qa6 qmz qn0']"))).text)

关于python - 如何使用selenium python单击 headless (headless)按钮并且按钮内部有div标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59420408/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com