2017-11-19 15 views
0

에 셀레늄 드라이버를 전달하는 방법? 내가 어떻게 이렇게 달릴 수 있을까? 따라서 작은 테스트 중 하나라도 실패하면 문제가있는 곳이 분명합니다.파이썬은 어떻게 내 코드를 실행할 때 나는이 오류가 계속 기능

generateRandomBroswerInfo() 
loginSite() 
getSomeInfo() 
quitBroswer() 

나는 내 코드

파이썬 3.6에 셀레늄을 사용하고 있습니다 : 당신은 genrateBroswer 내부 로컬 driver을 정의

from selenium import webdriver 
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities 
from selenium.common.exceptions import TimeoutException 
from selenium.webdriver.common.by import By 
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC 


def genrateBroswer(): 
    dcap = dict(DesiredCapabilities.PHANTOMJS) 
    dcap["phantomjs.page.settings.userAgent"] = ('Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3') 
    driver = webdriver.PhantomJS(desired_capabilities=dcap) 
    driver.set_window_size(300, 600) 

def letssee(): 
    driver.get('http://www.whatsmyip.org/') 
    driver.save_screenshot('this.png') 


genrateBroswer() 
letssee() 
#ETC 

답변

0

모든 필요한 방법으로 클래스를 사용할 수 있습니다 (Classes 참조). 예 : 한마디로

class Webdriver: 

    def __init__(self): 
     self.genrateBroswer() 
     self.letssee() 


    def genrateBroswer(self): 
     dcap = dict(DesiredCapabilities.PHANTOMJS) 
     dcap["phantomjs.page.settings.userAgent"] = ('Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3') 
     self.driver = webdriver.PhantomJS(desired_capabilities=dcap) 
     self.driver.set_window_size(300, 600) 

    def letssee(self): 
     self.driver.get('http://www.whatsmyip.org/') 
     self.driver.save_screenshot('this.png') 


# Creating an instance of the webdriver 
myWebsite = Webdriver() 

myWebsite.driver 

, 당신이 기능을 통해 사용하는 데 필요한 모든, 당신은 키워드 self로 저장하여 클래스의 속성을 확인해야합니다, 당신은 모든 기능에 self을 전달해야 수업.

+0

대답은 작동했기 때문에 표시했습니다. 그러나 내 문제를 해결 한 대답이 아닌 대신 변수 드라이버를 변수 글로브로 바꿨습니다. –

+0

@FutureHendrixs 클래스에서 벗어나고 싶다면 함수에'driver'를 전달하고 업데이트 된'driver'를 반환하여 bgse의 메서드를 사용하는 것이 좋습니다. –

0

, 당신이 그 기능을 중단하면, 그것은 사라 졌어요. 당신의 letssee 기능에

, 당신은 따라서 오류지고,이 시점에서 정의되지 않은 driver에 액세스하려고 :

NameError: name 'driver' is not defined 

내용에 대한 Python variables and scope 읽어 보시기 바랍니다.

또한 the Python tutorial을 확인하십시오.

+0

'genrateBroswer'에서'driver'를 꺼내서 두 번째 함수로로드 할 수 있습니까? & how –

+0

예를 들어 return 문을'genrateBroswer' 함수 끝에 추가 할 수 있습니다 :'return driver'를 호출하고'driver = genrateBroswer()'와 같이 호출하십시오. – bgse

+0

@FutureHendrixs 아주 기본적인 질문이기 때문에 [파이썬 튜토리얼] (https://docs.python.org/3/tutorial/)을 통해 작업 해 보시기 바랍니다. 불쾌감이 없다는 것을 의미합니다. 단지 두통과 맹신을 많이 줄여 줄 것입니다 :-) – bgse