селен, чтобы получить частичные скриншоты для каждого из элементов продукта на странице PLP - PullRequest
0 голосов
/ 28 февраля 2019

У меня есть приведенный ниже рабочий код в среде Mac OS Python3 Chrome vr (72.0) 64 бит. Он сохраняет только одно изображение за один раз.

У меня есть 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 голосов
/ 28 февраля 2019

Используйте цикл следующим образом:

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
...