此代码应该单击一个按钮(接受 cookie),然后截取页面的屏幕截图。它以正确的高度和宽度截取正确元素的屏幕截图,但在执行此操作之前不会单击按钮。
我所说的 cookie 按钮是“u.gg”上的按钮:
天哪,我讨厌我的生活按钮。单击是一个缺少的功能()我在这里坐了 4 个小时(我在 0:30 醒来)
最终代码:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
url = "https://u.gg/lol/champions/nunu/build"
options = Options()
options.add_argument("--start-maximized")
options.add_argument("--ignore-certificate-errors")
options.add_argument("--ignore-ssl-errors")
options.add_argument("--disable-web-security")
service = Service("chromedriver.exe")
driver = webdriver.Chrome(service=service, options=options)
try:
driver.get(url)
button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.CSS_SELECTOR, "button.fc-button.fc-cta-consent.fc-primary-button"))
)
button.click()
time.sleep(2)
element = driver.find_element(By.CLASS_NAME,"champion-recommended-build")
driver.execute_script("arguments[0].scrollIntoView();", element)
time.sleep(2)
screenshot_path = "uggscreenshot.png"
driver.save_screenshot(screenshot_path)
print(f"Screenshot saved to {screenshot_path}")
finally:
driver.quit()