【问题标题】:How to find coordinates of an element in iFrame - Python Selenium如何在 iFrame 中查找元素的坐标 - Python Selenium
【发布时间】:2020-03-22 02:02:57
【问题描述】:

我想通过截取整个网站的屏幕截图并裁剪它来截取 Tableau Public 可视化的屏幕截图。我能够找到我的元素的高度和宽度,但是我的 x 和 y 坐标是错误的。我假设 x = 0 和 y = 0 是我的元素在 iframe 中的坐标,而不是网站中的坐标。

如何获取 iframe 的坐标以便正确裁剪图像?目前它只是裁剪网站的左侧部分。

from selenium import webdriver
import time
from PIL import Image

driver = webdriver.Chrome(executable_path=r'C:\Program Files\chromedriver.exe')

# Maximise window and zoom out
driver.get('chrome://settings/')
driver.maximize_window()
driver.execute_script('chrome.settingsPrivate.setDefaultZoom(0.6);')

driver.get("https://public.tableau.com/en-gb/gallery/super-pac-origins?tab=viz-of-the-day&type=viz-of-the-day")

time.sleep(5)
driver.switch_to.frame(driver.find_element_by_tag_name("iframe"))

element = driver.find_element_by_xpath('//div[@id = "tab-dashboard-region"]')

location = element.location
print(location)
size = element.size 
print(size)

# Take a screenshot
driver.save_screenshot("C:\\Desktop\\Images_png\\test1.png")
time.sleep(2)

#Crop image
x = location['x']
y = location['y']
width = location['x']+ size['width']
height = location['y']+ size['height']

im = Image.open("C:\\Desktop\\Images_png\\test1.png")
im = im.crop((int(x), int(y), int(width), int(height)))
im.save("C:\\Desktop\\Images_png\\Crop\\test1.png")

# Close the current tab
driver.close()

感谢您的帮助。

【问题讨论】:

    标签: python selenium iframe


    【解决方案1】:

    我建议不要对所有网站进行截图,而是可以像这样定位元素并为该元素拍照:

    假设您要截取元素

    from io import BytesIO
    from PIL import Image
    
    img = element.screenshot_as_png
    stream = BytesIO(img)
    image = Image.open(stream).convert("RGB")
    image.save("imageTable.png")
    

    如果这能解决您的问题,请告诉我:P

    【讨论】:

    • 不知道你能做到这一点!唯一的问题是它似乎取决于缩放级别。它确实包含元素,但也包含网站的其他部分。
    • 可能你需要找到更深层次的元素。如果这个更深的元素在 iFrame 内,则需要在框架内切换。您可以按照post 中的说明实现这一目标
    【解决方案2】:

    我基于我所有的屏幕截图都具有相同尺寸的假设手动计算了位置:1920 * 899。

    #Crop image
    # 1920 is the width of the screenshot
    # 899 is the height of the screenshot
    # 0.74 considers the zoom factor
    
    left = (1920 - size['width']*0.74)/2
    right = left + size['width']*0.74
    top = 110 # Hardcoded because it's always the same value
    bottom = top + size['height']*0.74
    
    
    im = Image.open("C:\\Desktop\\Images_png\\test1.png")
    print(im.size)
    im = im.crop((left, top, right, bottom))
    im.save("C:\\Desktop\\Images_png\\Crop\\test1.png")
    

    【讨论】:

      猜你喜欢
      • 2017-08-05
      • 2021-05-03
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      • 1970-01-01
      • 2020-02-12
      • 2021-05-12
      • 1970-01-01
      相关资源
      最近更新 更多