无法获取宽度为0的屏幕截图

2024-06-28 10:54:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我想截取引导模式中元素的截图。经过一番挣扎,我终于想出了这样一个代码:

driver.get('https://enlinea.sunedu.gob.pe/')
driver.find_element_by_xpath('//div[contains(@class, "img_publica")]').click()

WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, 'modalConstancia')))
driver.find_element_by_xpath('//div[contains(@id, "modalConstancia")]').click()
active_element = driver.switch_to.active_element
active_element.find_elements_by_id('doc')[0].send_keys(graduate.id)

# Can't take this screenshot
active_element.find_elements_by_id('captchaImg')[0].screenshot_as_png('test.png')

错误是:

^{pr2}$

经过一番调试,我发现元素没有宽度和高度:

(Pdb) active_element.find_elements_by_id('captchaImg')[0].rect
{'height': 0, 'width': 0, 'x': 0, 'y': 0}
(Pdb) active_element.find_elements_by_id('captchaImg')[0].size
{'height': 0, 'width': 0}

我想这就是失败的原因。有办法绕过这个问题吗?在


步骤如下:

  1. 单击链接:

enter image description here

  1. 等待模态并填充第一个输入:

enter image description here

  1. 尝试截取验证码图片的截图:

enter image description here

如果我检查浏览器中的元素(保存CAPTCHA图像的span)我可以看到它实际上是100x50:

enter image description here


Tags: divid元素bydriverelementselementfind
1条回答
网友
1楼 · 发布于 2024-06-28 10:54:49

好的,我已经知道为什么你总是得到Cannot take screenshot with 0 width.错误。原因是页面上有多个验证码,使用非特定的选择器会给您一个隐藏的验证码图像(可能在另一个模式窗口下)。所以增加特异性会给你正确的图像。在

代码如下:

from contextlib import contextmanager
from logging import getLogger

from selenium.common.exceptions import TimeoutException
from selenium.webdriver import Chrome, ChromeOptions
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

logger = getLogger(__name__)


@contextmanager
def get_chrome() -> Chrome:
    opts = ChromeOptions()
    # opts.headless = True
    logger.debug('Running Chrome')
    driver = Chrome(options=opts)
    driver.set_window_size(1000, 600)
    logger.debug('Chrome started')
    yield driver
    driver.close()


def wait_selector_present(driver: Chrome, selector: str, timeout: int = 5):
    cond = EC.presence_of_element_located((By.CSS_SELECTOR, selector))
    try:
        WebDriverWait(driver, timeout).until(cond)
    except TimeoutException as e:
        raise ValueError(f'Cannot find {selector} after {timeout}s') from e


def wait_selector_visible(driver: Chrome, selector: str, timeout: int = 5):
    cond = EC.visibility_of_any_elements_located((By.CSS_SELECTOR, selector))
    try:
        WebDriverWait(driver, timeout).until(cond)
    except TimeoutException as e:
        raise ValueError(f'Cannot find any visible {selector} after {timeout}s') from e


if __name__ == '__main__':
    with get_chrome() as c:
        captcha_sel = '#consultaForm #captchaImg img'
        modal_sel = '[data-target="#modalConstancia"]'

        url = 'https://enlinea.sunedu.gob.pe/'
        c.get(url)

        wait_selector_present(c, modal_sel)
        modal = c.find_element_by_css_selector(modal_sel)
        modal.click()

        wait_selector_visible(c, captcha_sel)
        captcha_img = c.find_element_by_css_selector(captcha_sel)
        captcha_img.screenshot('captcha.png')

结果:

enter image description here

相关问题 更多 >