python realizes automatic web page screenshots and cropping images

  • 2020-11-26 18:52:24
  • OfStack

This article shares the python automatic webpage screenshot and cut the specific code of the picture for your reference, the specific content is as follows

Code:


# coding=utf-8
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from PIL import Image
import os

all_urls = ['http:/****edit']
def login():
  chrome_options = Options()
  chrome_options.add_argument('--headless')
  driver = webdriver.Chrome(executable_path='./chromedriver',chrome_options=chrome_options)
  driver.set_window_size(1200, 741)
  driver.implicitly_wait(2)
  print(' In the initialization ...')
  driver.get("http://x*****e")
  print(' Fill in the login information ...')
  acc = driver.find_element_by_id('login-email')
  pwd = driver.find_element_by_id('login-pass')
  btn = driver.find_element_by_tag_name('button')
  acc.send_keys('***')
  pwd.send_keys('***')
  btn.click()
  print(' Jump to the captcha page ...')
  time.sleep(2)
  capta = driver.find_element_by_id('code')
  capta_input = input(' Please enter the two-step verification code: ')
  capta.send_keys(capta_input)
  btn1 = driver.find_element_by_tag_name('button')
  btn1.click()
  time.sleep(2)
  print(' Jump to the creative Editing page ...')
  return driver

def get_screen(driver,urls):
  count = 1
  for url in urls:
    driver.get(url)
    print(' Is fetching --> %s'% url)
    count +=1
    time.sleep(2)
    uid = url.split('/')[-2]
    cid = url.split('/')[-5]
    driver.get_screenshot_as_file("./screen_shot/{}-{}.png".format(uid,cid))
    print(" creative --> {}-{}.png  Has been saved ".format(uid,cid))
    print(' And then there were  %s  a '% str(len(urls)-count))

def crop_img():
  for img in os.listdir('./screen_shot'):
    if img.endswith('.png'):
      print('%s Cut out. '% img)
      im = Image.open('./screen_shot/%s'% img)
      x = 755
      y = 162
      w = 383
      h = 346
      region = im.crop((x, y, x+w, y+h))
      region.save("./screenshot_final/%s" % img)


if __name__ == '__main__':
  driver = login()
  get_screen(driver,all_urls)
  driver.quit()
  print(' All grab ends ')
  crop_img()
  print(' All clipping ends ')

Related articles: