如果我用python编写的程序允许使用mechanize到automatically browse a given website来检测是否存在使用Python的弹出窗口(建议广告或下载操作…),是否有可能?我将不胜感激(例如,如果您给我一个可以完成此任务的图书馆,我将非常高兴)
解决方法:
机械化无法处理javascript和弹出窗口:
> How do I use Mechanize to process JavaScript?
> Mechanize and Javascript
要实现该目标,您需要使用一个真实的浏览器,无论是否使用headless.这是selenium
可以提供帮助的地方.它具有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()
示例(使用此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()
也可以看看:
> Handle Popup Windows
> Click the javascript popup through webdriver