2

I encounter a small problem using Selenium on Python. In my main script, which is the following (right down), I would just like to manage to execute another external python script.

import time, os
import re #regex
import uuid
import urllib
import subprocess, sys
import pyautogui
import PIL
from PIL import Image 
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains  import ActionChains
def download():
    urllib.urlretrieve(m, "images/imgOUI_"+unique_filename+".png")
    im = Image.open("images/imgOUI_"+unique_filename+".png")
    out = im.resize((int(ExtractResize), int(ExtractResize2)))
    out.save("images/ImgComplete_"+unique_filename+".png")
co = webdriver.ChromeOptions()
co.add_argument("--user-data-dir=C:\Users\Marshall\AppData\Local\Google\Chrome\User Data\Default")
browser = webdriver.Chrome(chrome_options = co) 
browser.get("http://*/")
browser.find_element_by_id('SubmitButton').click()
#----------Move iframe-------
try:
    wait(browser, 20).until(EC.frame_to_be_available_and_switch_to_it(browser.find_element_by_xpath('//iframe[contains(@src, "google.com/recaptcha")]')))
except:
    print("error")

[...]
while True:

    [...]
    link = wait(browser, 20).until(EC.presence_of_all_elements_located((By.XPATH, '//img[contains(@src, "https://www.google.com/recaptcha/api2/payload?")]')))
    listLink = [] 
    for k in link:
        m = k.get_attribute('src')
        if m in listLink:
            print("Already added")
        else:
        listLink.insert(0, m)
        test = k.value_of_css_property("height") 
        test2 = k.value_of_css_property("width")
        ExtractResize = test.replace('px', '')
        ExtractResize2 = test2.replace('px', '')

        unique_filename = str(uuid.uuid4())
        download() 

        dim = wait(browser, 20).until(EC.presence_of_element_located((By.XPATH, '//div[contains(@style, "width")]'))).get_attribute('style')
        int1, int2 = re.findall(r'\d+', dim)
        subprocess.check_call("cut.py", shell=True) #Here, i want execute my other script python

(I spent some moments of my code which seems useless to add, if necessary, I would add them!)

Here the code of cut.py:

import time
from se import *
import random
import PIL
import uuid
from PIL import Image 
def cut():
    im = Image.open("images/ImgComplete_"+unique_filename+".png")


    left = a
    top = b
    width = c
    height = d



    box = (left, top, left+width, top+height)



    area = im.crop(box)


    print area.size
    unique_filename = str(uuid.uuid4())
    print unique_filename
    area.save("images/Principales/IMGsepare_"+unique_filename+".png")



image_size = (int(ExtractResize), int(ExtractResize2))

portion_size = (int(int1), int(int2))

Test2 = image_size[0]/portion_size[0]
Test = image_size[0]/float(portion_size[0])

List = (0, 0, portion_size[0], portion_size[1])
a, b, c, d = List
while True:
    if a==0:
        cut()
    for mo in range(0, int(Test2)):
        a += portion_size[0]
        if a == (int(Test2) * portion_size[0]):
            break
        cut()
    if a == (int(Test2) * portion_size[0]): 
        if not Test2 == Test:

            a = (image_size[0] - portion_size[0])
            cut()
        a = 0


        if b == (int(Test2) * portion_size[0]) and not Test2 == Test: 
            b = (image_size[1] - portion_size[1])

        else:   
            if b == image_size[1]: 
                print("Break")
                break
            print b
            b += portion_size[0] 
            if b == (int(Test2) * portion_size[0]) and not Test2 == Test: 
                b = (image_size[1] - portion_size[1])
                print("Vient de reajuster le B")
            print b
        if b == image_size[1]: 
            print("Break")
            break               

So I tried several methods, such as the following:

  • subprocess.call("cut.py", shell = False)
  • os.system("start cut.py")
  • execfile("cut.py")

In all these attempts, I noticed that my program adopted the same behavior: In fact, it simply turns on another blank google window, then nothing, nothing happens.

I do not understand at all what comes from this problem.

EDIT:

After several minutes I finally get an error, here is the screen: enter image description here

6
  • So to cut everything short, you want to run another python file from your current python file? And rest of the code you posted is not of importance? Commented Aug 12, 2017 at 21:06
  • That's right ! But the fact that my script opens another blank web page seems strange to me when I try to run my other script ... That's why I prefer to link my code Commented Aug 12, 2017 at 21:12
  • what does the cut.py do? Commented Aug 12, 2017 at 21:13
  • It downloads the image just been extracted, and cuts the latter with a certain pattern. So I do not use selenium in cut.py Commented Aug 12, 2017 at 21:17
  • "It downloads the image just extracted" - how does it achieve it? :) Please post cut.py code. Thanks Commented Aug 12, 2017 at 21:18

1 Answer 1

0

So I have a test.py with below content

print("test")

I can run this file using below possible options

>>> import subprocess
>>> subprocess.check_call(["python3", "./test.py"])
test.py
0
>>> subprocess.check_output(["python3", "./test.py"])
'test.py\n'
>>>

Use the one which suits you. To understand the difference between the two read the below thread

Python subprocess .check_call vs .check_output

Next you have a approach problem in your code also. In your cut.py you have from se import *. This includes your main file in cut.py. You should change your file as below

from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait as wait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains  import ActionChains
def download():
    urllib.urlretrieve(m, "images/imgOUI_"+unique_filename+".png")
    im = Image.open("images/imgOUI_"+unique_filename+".png")
    out = im.resize((int(ExtractResize), int(ExtractResize2)))
    out.save("images/ImgComplete_"+unique_filename+".png")

def main():
    co = webdriver.ChromeOptions()
    co.add_argument("--user-data-dir=C:\Users\Marshall\AppData\Local\Google\Chrome\User Data\Default")
    browser = webdriver.Chrome(chrome_options = co) 
    browser.get("http://*/")
    browser.find_element_by_id('SubmitButton').click()
    #----------Move iframe-------
    try:
        wait(browser, 20).until(EC.frame_to_be_available_and_switch_to_it(browser.find_element_by_xpath('//iframe[contains(@src, "google.com/recaptcha")]')))
    except:
        print("error")

    [...]
    while True:

        [...]
        link = wait(browser, 20).until(EC.presence_of_all_elements_located((By.XPATH, '//img[contains(@src, "https://www.google.com/recaptcha/api2/payload?")]')))
        listLink = [] 
        for k in link:
            m = k.get_attribute('src')
            if m in listLink:
                print("Already added")
            else:
            listLink.insert(0, m)
            test = k.value_of_css_property("height") 
            test2 = k.value_of_css_property("width")
            ExtractResize = test.replace('px', '')
            ExtractResize2 = test2.replace('px', '')

            unique_filename = str(uuid.uuid4())
            download() 

            dim = wait(browser, 20).until(EC.presence_of_element_located((By.XPATH, '//div[contains(@style, "width")]'))).get_attribute('style')
            int1, int2 = re.findall(r'\d+', dim)
            subprocess.check_call("cut.py", shell=True) #Here, i want execute my other script python

if __name__ == "__main__":
   main()

If you import a file then it should not have globally executing code

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks :) But this method does not work in my script (A new page opens, then that's all ...) I don't know why
A screenshot of the issue would be more helpful
After several minutes I finally get an error, here is the screen: prntscr.com/g7qoxv
Thanks you very much ! I did not know that it was necessary to do so .. This help was very useful for me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.