Мой скрипт ищет различные файлы cookie селекторы кнопок согласия и нажимают соответствующую кнопку с использованием выполнения JavaScript. Однако, несмотря на то, что кнопка присутствует и выглядит доступной для нажатия, событие нажатия не всегда срабатывает.
Вот соответствующий код Python
Код: Выделить всё
import logging
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
from selenium.common.exceptions import NoSuchElementException, TimeoutException
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def handle_cookie_consent(driver):
selectors = [
"//button[@data-testid='uc-accept-all-button']",
"//button[contains(text(), 'Geht klar')]",
"//button[contains(text(), 'Alles akzeptieren')]",
"//button[contains(text(), 'Accept all')]",
"//button[contains(text(), 'Accept')]"
]
try:
# Check if the cookie consent button is inside an iframe
iframes = driver.find_elements(By.TAG_NAME, "iframe")
for iframe in iframes:
driver.switch_to.frame(iframe)
for selector in selectors:
try:
accept_button = WebDriverWait(driver, 22).until(
EC.element_to_be_clickable((By.XPATH, selector))
)
# Use JavaScript to click the button
driver.execute_script("arguments[0].click();", accept_button)
time.sleep(2)
logger.info(f"Accepted cookie consent using selector: {selector}")
driver.switch_to.default_content()
return
except (NoSuchElementException, TimeoutException):
driver.switch_to.default_content()
continue
# If the button is not inside an iframe, try to find it in the main content
for selector in selectors:
try:
accept_button = WebDriverWait(driver, 2).until(
EC.element_to_be_clickable((By.XPATH, selector))
)
# Use JavaScript to click the button
driver.execute_script("arguments[0].click();", accept_button)
time.sleep(2)
logger.info(f"Accepted cookie consent using selector: {selector}")
return
except (NoSuchElementException, TimeoutException):
continue
logger.info("No cookie consent button found.")
except Exception as e:
logger.error(f"Error handling cookie consent: {e}")
def main():
# Set up the WebDriver (e.g., using Chrome)
driver = webdriver.Chrome()
try:
# Open the website
driver.get("https://www.zalando.de")
# Handle cookie consent
handle_cookie_consent(driver)
# Print the title of the page
print("Page title is:", driver.title)
finally:
# Close the WebDriver
driver.quit()
if __name__ == "__main__":
main()
Подробнее здесь: https://stackoverflow.com/questions/793 ... ng-visible
Мобильная версия