我正在尝试通过点击按钮订阅此 reddit 页面。
我已在检查模式下打开页面,找到该按钮并将其 XPATH 复制到下面的代码中。 但是代码说找不到该元素。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
URL = "https://www.reddit.com/r/learnjavascript"
driver = webdriver.Chrome()
driver.get(URL)
time.sleep(5)
driver.find_element(By.XPATH, "/div/faceplate-tracker").click()
driver.find_element(By.XPATH, "/div/faceplate-tracker").click()
问题:
XPath 表达式不正确。下面的一些参考资料供您阅读和理解 XPath。
目标元素(“加入”按钮)位于嵌套的影子根元素内。在尝试与目标元素交互之前,您需要先处理影子根。以下是您的信息参考:
检查下面的代码并点击“加入”按钮:
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
URL = "https://www.reddit.com/r/learnjavascript"
driver = webdriver.Chrome()
driver.get(URL)
time.sleep(5)
root1=driver.find_element(By.CSS_SELECTOR, "shreddit-subreddit-header-buttons").shadow_root
root2=root1.find_element(By.CSS_SELECTOR, "shreddit-join-button").shadow_root
join_Btn=root2.find_element(By.CSS_SELECTOR, "[class=' button-primary button-medium button join-btn leading-none px-sm py-xs ']")
join_Btn.click()
time.sleep(10)
修改代码并应用selenium waits以有效定位元素。 检查下面的代码:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
URL = "https://www.reddit.com/r/learnjavascript"
driver = webdriver.Chrome()
driver.get(URL)
driver.maximize_window()
wait = WebDriverWait(driver, 15)
root1=wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "shreddit-subreddit-header-buttons"))).shadow_root
root2=WebDriverWait(root1, 15).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "shreddit-join-button"))).shadow_root
join_Btn = WebDriverWait(root2, 15).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "[class=' button-primary button-medium button join-btn leading-none px-sm py-xs ']")))
join_Btn.click()
time.sleep(10)