簡體   English   中英

如何使用selenium python單擊無頭按鈕和按鈕內部有div標簽?

[英]how to click button in headless and button have div tag inside it using selenium python?

使用此代碼無需無頭方法.. 網站鏈接: 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-tag,所以它不能用於無頭和虛擬顯示。

我也嘗試等待:

    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
谷歌瀏覽器 78.0.3904.108

觸發任何事件時使用無頭模式 add window-size() 因為無頭瀏覽器無法識別沒有窗口大小的點擊位置。

單擊Load more products按鈕 Induce 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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM