2016-09-30 6 views
2

나는 파이썬으로 경고를 처리하는 것을 좋아한다. 내가 뭘 좋아 wuold 것은 :Python으로 경고를 처리하는 방법은 무엇입니까?

  • 열기
  • 양식을 제출 또는 경고가 나는 Javascript 이것을 만든

새 페이지에 발생하는 경우 몇 가지 링크를

  • 확인을 클릭 URL PhantomJS을 사용했지만, 파이썬에서도 마찬가지였다.

    파일 test.js :

    var webPage = require('webpage'); 
    var page = webPage.create(); 
    
    var url = 'http://localhost:8001/index.html' 
    
    page.onConsoleMessage = function (msg) { 
        console.log(msg); 
    }  
    page.open(url, function (status) {     
        page.evaluate(function() { 
         document.getElementById('myButton').click()  
        });   
        page.onConsoleMessage = function (msg) { 
         console.log(msg); 
        }  
        page.onAlert = function (msg) { 
         console.log('ALERT: ' + msg); 
        };  
        setTimeout(function() { 
         page.evaluate(function() { 
          console.log(document.documentElement.innerHTML) 
         }); 
         phantom.exit(); 
        }, 1000); 
    }); 
    

    파일

    <!DOCTYPE html> 
    <html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 
        <title></title> 
        <meta charset="utf-8" /> 
    </head> 
    <body onload="alert('hello')"> 
    </body> 
    </html> 
    

    이 작품 파일 page2.html

    <!DOCTYPE html> 
    <html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> 
        <title></title> 
        <meta charset="utf-8" /> 
    </head> 
    <body> 
        <form> 
         <input id="username" name="username" /> 
         <button id="myButton" type="button" value="Page2">Go to Page2</button> 
        </form> 
    </body> 
    </html> 
    
    <script> 
        document.getElementById("myButton").onclick = function() { 
         location.href = "page2.html"; 
        }; 
    </script> 
    

    index.html을 여기

    는 자바 스크립트 코드 ; page2.html에서 경고를 감지합니다. 경고가 파이썬 page2.html에 발생하는 경우 제가 확인할 수있는 방법,

    test.py 이제

    import requests 
    from test import BasicTest 
    from selenium import webdriver 
    from bs4 import BeautifulSoup 
    
    url = 'http://localhost:8001/index.html'  
    
    def main(): 
        #browser = webdriver.Firefox() 
        browser = webdriver.PhantomJS() 
        browser.get(url) 
        html_source = browser.page_source 
        #browser.quit()  
        soup = BeautifulSoup(html_source, "html.parser") 
        soup.prettify()  
        request = requests.get('http://localhost:8001/page2.html') 
        print request.text  
        #Handle Alert  
    if __name__ == "__main__": 
        main(); 
    

    : 지금 나는이 파이썬 스크립트를 만들어? 먼저 index.html 페이지를 연 다음 page2.html 페이지를 엽니 다. 저는 처음에 모든 제안을 감사하게 생각합니다.

    p.s. 나는 또한 webdriver.Firefox()를 테스트했지만 매우 느립니다. 나는 또한이 질문을 읽었다 : Check if any alert exists using selenium with python

    그러나 작동하지 않는다 (아래의 이전 스크립트와 답에서 제안 된 해결책이 더 함).

    :

    .....  
    from selenium.webdriver.support.ui import WebDriverWait 
    from selenium.webdriver.support import expected_conditions as EC 
    from selenium.common.exceptions import TimeoutException 
    
    .... 
    
    def main(): 
        ..... 
        #Handle Alert 
        try: 
         WebDriverWait(browser, 3).until(EC.alert_is_present(), 
                 'Timed out waiting for PA creation ' + 
                 'confirmation popup to appear.') 
    
         alert = browser.switch_to.alert() 
         alert.accept() 
         print "alert accepted" 
        except TimeoutException: 
         print "no alert" 
    
    if __name__ == "__main__": 
        main(); 
    

    내가 오류 얻을 "selenium.common.exceptions.WebDriverException : 메시지 : 잘못된 명령 방법을 ..."

  • 답변

    1

    PhantomJS를 WebDriver 와이어를 구현하는 GhostDriver를 사용 프로토콜은 셀레늄에서 헤드리스 브라우저로 작동하는 방식입니다.

    유감스럽게도 GhostDriver는 현재 알리미를 지원하지 않습니다. 것처럼 보이지만 그들은 기능을 구현하는 데 도움이 필요 :

    https://github.com/detro/ghostdriver/issues/20

    당신은 아마도 PhantomJS의 자바 스크립트 버전으로 전환 또는 셀레늄 내 파이어 폭스 드라이버를 사용할 수 있습니다.

    from selenium import webdriver 
    from selenium.common.exceptions import NoAlertPresentException 
    
    if __name__ == '__main__': 
        # Switch to this driver and switch_to_alert will fail. 
        # driver = webdriver.PhantomJS('<Path to Phantom>') 
        driver = webdriver.Firefox() 
        driver.set_window_size(1400, 1000) 
        driver.get('http://localhost:8001/page2.html') 
    
        try: 
         driver.switch_to.alert.accept() 
         print('Alarm! ALARM!') 
        except NoAlertPresentException: 
         print('*crickets*') 
    
    +0

    안녕하세요! 답변 해주셔서 감사합니다. 솔루션을 실행하려했지만 작동하지 않습니다. 빈 페이지가 열리고 아무 일도 일어나지 않습니다. 내가 놓친 게 있니? – d3llafr33

    +0

    스크립트는 파이썬 3.5 인터프리터를 사용하여 실행됩니다.'__main__'아래의 코드를 복사하여 붙여 넣는 것이 좋습니다. 가져 오기 문은 자신의 스크립트에 넣으십시오. 올바르게 실행되면 URL에 firefox 창을 열고 두 메시지 중 하나를 콘솔에 인쇄해야합니다. – jinksPadlock

    +0

    파이썬 2.7을 사용하고있었습니다. Python 3.5로 바꾸었지만 결과는 같습니다. 나는 또한 당신의 제안을 따랐다. 나는 셀레늄 v.2.53.6을 사용하고있다 – d3llafr33

    관련 문제