I’m trying to automate interaction with the pure.app website using Selenium WebDriver in Python. The main goal is to automatically like posts on the website, but in order to do that, I need to be able to scroll the page to load new content.
However, I’m facing an issue where the scrolling functionality is not working as expected. I’ve tried several approaches, including:
- Using
driver.execute_script("window.scrollBy(0, 500)")
to scroll the page by 500 pixels. - Utilizing
ActionChains(driver).send_keys(Keys.PAGE_DOWN).perform()
to simulate pressing the Page Down key. - Implementing a custom
smooth_scroll()
function that scrolls the page gradually using a JavaScript interval.
Despite these attempts, the page does not seem to scroll at all, and the content remains static. The code runs without any errors, but the page content does not change.
I’ve checked the website’s structure and haven’t found any obvious obstacles to scrolling, such as dynamic content loading or infinite scrolling. The page content appears to be static and should be scrollable.
Can you help me identify the root cause of this issue and provide a solution to successfully scroll the pure.app website using Selenium WebDriver?
Code
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
# Настройка опций Chrome
chrome_options = Options()
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
chrome_options.add_experimental_option('useAutomationExtension', False)
# Путь к ChromeDriver
chrome_driver_path = r'C:chromedriver-win64chromedriver.exe'
# Инициализация драйвера
service = Service(chrome_driver_path)
driver = webdriver.Chrome(service=service, options=chrome_options)
# Установка размера окна браузера
driver.set_window_size(1920, 1080)
# Функция для поиска и нажатия кнопки "лайк"
def find_and_click_like_button():
like_button_selector = "div.sc-nukQN button.sc-koXPp.sc-bmzYkS:nth-child(3)"
try:
like_button = WebDriverWait(driver, 5).until(
EC.presence_of_element_located((By.CSS_SELECTOR, like_button_selector))
)
# Проверяем, не был ли уже поставлен лайк
svg = like_button.find_element(By.TAG_NAME, "svg")
if "fill: red" not in svg.get_attribute("outerHTML"):
driver.execute_script("arguments[0].click();", like_button)
print("Кнопка 'лайк' нажата.")
return True
else:
print("Лайк уже поставлен, пропускаем.")
return False
except Exception as e:
print(f"Кнопка 'лайк' не найдена или не может быть нажата: {e}")
return False
# Функция для плавной прокрутки
def smooth_scroll(distance):
script = f"""
var current = 0;
var interval = setInterval(function() {{
window.scrollBy(0, 10);
current += 10;
if (current >= {distance}) clearInterval(interval);
}}, 20);
"""
driver.execute_script(script)
try:
# Открываем страницу входа Google
driver.get("https://accounts.google.com/")
# Ввод email
email_input = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, "input[type='email']"))
)
email_input.send_keys("XXXXXXXXXXXXXXXXXX")
email_input.send_keys(Keys.RETURN)
print("Email введен.")
# Добавляем паузу после ввода логина
time.sleep(10)
print("Ожидание 10 секунд после ввода email.")
# Ожидание и ввод пароля
password_input = WebDriverWait(driver, 20).until(
EC.presence_of_element_located((By.CSS_SELECTOR, "input[type='password']"))
)
password_input.send_keys("XXXXXXXXXXXXXXXX")
print("Пароль введен.")
# Ожидание кнопки "Далее" после ввода пароля
next_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "//button[@jsname='LgbsSe']//span[text()='Далее']"))
)
driver.execute_script("arguments[0].click();", next_button)
print("Кнопка 'Далее' нажата.")
# Ожидание завершения входа
time.sleep(15)
print("Вход в Google выполнен.")
# Переход на pure.app
driver.get("https://pure.app/ru/")
print("Переход на pure.app выполнен.")
# Ожидание загрузки страницы
WebDriverWait(driver, 30).until(
EC.presence_of_element_located((By.ID, "hamburger-btn"))
)
# Клик по кнопке меню
hamburger_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.ID, "hamburger-btn"))
)
driver.execute_script("arguments[0].click();", hamburger_button)
print("Клик по кнопке меню выполнен.")
# Клик по кнопке SIGN IN
sign_in_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.ID, "menu-sign-in"))
)
driver.execute_script("arguments[0].click();", sign_in_button)
print("Клик по кнопке SIGN IN выполнен.")
# Клик по кнопке "С Google"
google_login_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "//button[contains(@class, 'block uppercase h-[49px]') and contains(., 'С google')]"))
)
driver.execute_script("arguments[0].click();", google_login_button)
print("Клик по кнопке 'С Google' выполнен.")
print("Вход на pure.app выполнен.")
# Ожидание загрузки страницы после входа
time.sleep(10)
print("Ожидание 10 секунд после входа.")
# Нажатие кнопки "РАЗРЕШИТЬ"
try:
allow_button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "//a[contains(@class, 'sc-dtInlm') and contains(@class, 'sc-kGCWdC')]//span[text()='РАЗРЕШИТЬ']"))
)
driver.execute_script("arguments[0].click();", allow_button)
print("Кнопка 'РАЗРЕШИТЬ' нажата.")
except Exception as e:
print(f"Не удалось нажать кнопку 'РАЗРЕШИТЬ': {e}")
# Дополнительное ожидание после нажатия "РАЗРЕШИТЬ"
time.sleep(5)
# Основной цикл для постоянного лайканья
scroll_distance = 0
while True:
# Поиск и нажатие кнопки "лайк"
if find_and_click_like_button():
time.sleep(1) # Пауза после успешного лайка
# Эмуляция плавной прокрутки с помощью JavaScript
smooth_scroll(500)
print("Прокрутка страницы на 500 пикселей.")
time.sleep(2) # Ожидание загрузки новых анкет
# Проверка на желание пользователя остановить процесс
user_input = input("Нажмите Enter для продолжения или введите 'stop' для остановки: ")
if user_input.lower() == 'stop':
print("Процесс остановлен пользователем.")
break
except Exception as e:
print("Ошибка:", e)
# Ожидание ввода перед закрытием
input("Нажмите Enter для завершения...")
# Закрытие браузера
driver.quit()
Any insights or suggestions would be greatly appreciated.