I'm trying to subscribe to this reddit page via a click button.
I have opened the page in inspect mode, located the button and copied its XPATH into the code below. But the code is saying it cannot find the element.
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()
Issues:
XPath expression is incorrect. Few references below for you to read and understand about XPaths.
The target element("Join" button) is within a nested shadow root element. You need to deal with shadow roots first before trying to interact with the target element. Few references below for your info:
Check the code below to click on "Join" button:
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)
Code modified and applied selenium waits to effectively locate elements. Check code below:
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)