硒以获取PLP页面中每个产品元素的部分屏幕截图

时间:2019-02-28 04:13:55

标签: python image selenium python-imaging-library

在64位Mac OS Python3 Chrome vr(72.0)环境中,我具有以下工作代码。每次只能保存一张图像。

我有xpath,希望以这样的模式进行屏幕截图:

  • // * [@ id =“ products-container”] / div [1] / div [2] / div [1]
  • 。 。 。
  • // * [@ id =“ products-container”] / div [1] / div [2] / div [40]

我要这样保存屏幕截图

  • image1.png
  • ...
  • image40.png

如果有人可以,请提供一些有用的建议。

from selenium import webdriver
from PIL import Image
from io import BytesIO
import os
import time
from random import randint
from time import sleep

driver = webdriver.Chrome('/Users/Documents/python/Selenium/bin/chromedriver')
driver.get('website-PLP')

element = driver.find_element_by_xpath("//*[@id='products-container']/div[1]/div[2]/div[40]") # find part of the page you want image of

location = element.location_once_scrolled_into_view
size = element.size
png = driver.get_screenshot_as_png() # saves screenshot of entire page

im = Image.open(BytesIO(png)) # uses PIL library to open image in memory

left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']
im = im.crop((left, top, right, bottom)).save('image40.png') # defines crop points

sleep(randint(3,3))

driver.quit()

1 个答案:

答案 0 :(得分:1)

按如下所示使用循环:

i = 1

while i < 41:
    element = driver.find_element_by_xpath("//*[@id='products-container']/div[1]/div[2]/div["+i+"]") # find part of the page you want image of

    location = element.location_once_scrolled_into_view
    size = element.size
    png = driver.get_screenshot_as_png() # saves screenshot of entire page

    im = Image.open(BytesIO(png)) # uses PIL library to open image in memory

    left = location['x']
    top = location['y']
    right = location['x'] + size['width']
    bottom = location['y'] + size['height']
    im = im.crop((left, top, right, bottom)).save("image"+i+".png")
    i=i+1