无法使用Selenium导入外部Python程序

无法使用Selenium导入外部Python程序,python,selenium,automation,Python,Selenium,Automation,我在Python上使用Selenium时遇到了一个小问题。 在我的主脚本(如下所示)中,我只想执行另一个外部python脚本 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 se

我在Python上使用Selenium时遇到了一个小问题。 在我的主脚本(如下所示)中,我只想执行另一个外部python脚本

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
(我花了一些时间编写代码,这些代码似乎无法添加,如果有必要,我会添加它们!)

下面是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               
所以我尝试了几种方法,比如:

  • 子进程调用(“cut.py”,shell=False)
  • 操作系统(“start cut.py”)
  • execfile(“cut.py”)
在所有这些尝试中,我注意到我的程序采用了相同的行为:事实上,它只是打开另一个空白的谷歌窗口,然后什么都没有,什么都没有发生

我完全不明白这个问题会带来什么

编辑:


几分钟后,我终于发现一个错误,屏幕如下:

所以我有一个
test.py
和下面的内容

print("test")
我可以使用以下可能的选项运行此文件

>>> import subprocess
>>> subprocess.check_call(["python3", "./test.py"])
test.py
0
>>> subprocess.check_output(["python3", "./test.py"])
'test.py\n'
>>>
用一个适合你的。要理解两者之间的区别,请阅读下面的线程

接下来,代码中还有一个方法问题。在
cut.py
中,您拥有来自se导入的
*
。这包括
cut.py
中的主文件。您应该按以下方式更改您的文件

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()

如果您导入一个文件,那么它不应该有全局执行的代码

,因此为了简化所有内容,您想从当前的python文件运行另一个python文件吗?你发布的其他代码并不重要?没错!但当我试图运行另一个脚本时,脚本打开另一个空白网页的事实对我来说似乎很奇怪。。。这就是为什么我更喜欢链接我的代码
cut.py
做什么?它下载刚刚提取的图像,并以某种模式剪切后者。因此,我不在cut.py中使用selenium“它下载刚刚提取的图像”-它是如何实现的?:)请发布cut.py代码。谢谢Hanks:)但是这个方法在我的脚本中不起作用(打开一个新页面,就这样…)我不知道为什么这个问题的截图会更有用几分钟后我终于得到一个错误,这是屏幕:非常感谢!我不知道有必要这样做。。这个帮助对我非常有用!