How to check for webpages' popups?

前端 未结 2 962
误落风尘
误落风尘 2021-01-16 12:02

Is there a possibility if I code a program in python that allows to automatically browse a given website using mechanize to detect if there are popup windows (suggesting adv

2条回答
  •  佛祖请我去吃肉
    2021-01-16 12:46

    Mechanize cannot handle javascript and popup windows:

    • How do I use Mechanize to process JavaScript?
    • Mechanize and Javascript

    To accomplish the goal, you need to utilize a real browser, headless or not. This is where selenium would help. It has a built-in support for popup dialogs:

    Selenium WebDriver has built-in support for handling popup dialog boxes. After you’ve triggerd and action that would open a popup, you can access the alert with the following:

    alert = driver.switch_to_alert()

    Example (using this jsfiddle):

    from selenium import webdriver
    
    url = "http://fiddle.jshell.net/ebkXh/show/"
    driver = webdriver.Firefox()
    driver.get(url)
    
    button = driver.find_element_by_xpath('//button[@type="submit"]')
    
    # dismiss
    button.click()
    driver.switch_to.alert.dismiss()
    
    # accept
    button.click()
    driver.switch_to.alert.accept()
    

    See also:

    • Handle Popup Windows
    • Click the javascript popup through webdriver

提交回复
热议问题