Mac Book Pro视网膜显示屏上的枕头

时间:2018-10-21 17:17:53

标签: python selenium python-imaging-library

我目前正在尝试在Python 2.7上使用Selenium和Pillow拍摄特定Web元素的屏幕截图。我拥有的代码似乎能够截取屏幕截图,然后裁剪图像,但实际上并没有在元素的确切位置裁剪。经过研究,我发现这可能是由于Mac Book Pro视网膜显示器使用的dpi而引起的,但是我没有找到解决方法。

用视网膜显示器和PIL处理这种“问题”的最佳方法是什么?

这是我正在使用的代码:

try:
    #Wait until finishing loading
    waitElement = WebDriverWait(driver,60).until(
           EC.presence_of_element_located((By.XPATH, "//*[@id='someElement']/span/input[2]"))
    )
    try:
            #Go to trends report
            driver.get("https://somewebsite.com/trends")
            waitElement = WebDriverWait(driver,60).until(
            EC.presence_of_element_located((By.ID, "Totals"))
            )

            try:

                    summary = driver.find_element_by_id("Totals")
                    driver.save_screenshot("sc.png")
                    location = summary.location
                    size = summary.size
                    x = location['x']
                    y = location['y']
                    w = size['width']
                    h = size['height']
                    width = x + w
                    height = y + h
                    im = Image.open('sc.png')
                    im = im.crop((int(x), int(y), int(width), int(height)))
                    im.save('summary.png')

            except NoSuchElementException:
                    print("Something")
    except NoSuchElementException:
            print("Something")
finally:
       driver.close()

1 个答案:

答案 0 :(得分:0)

我遇到了这个问题(如果在Mac上显示Ratina,则屏幕截图出现问题)并使用

解决了

我用于此的代码段

//基本上,这里我使用'devicePixelRatio'计算正确的宽度/高度

    WebElement ele = findElement(By.xpath(webElementXpath));
    Point point = ele.getLocation();
    int devicePixelRatio = Integer.parseInt(returnExecuteJavaScript("return window.devicePixelRatio"));
    int eleWidth = ele.getSize().getWidth() * devicePixelRatio;
    int eleHeight = ele.getSize().getHeight() * devicePixelRatio;
    // ....... for cropping stuff , you can use your own code