我开始学习Selenium(使用Python),当驱动程序打开网站时会显示弹出广告。我尝试使用以下方法关闭它:
try:
if driver.switch_to_alert() != None:
clink = driver.find_element_by_id("CloseLink")
clink.click()
driver.implicitly_wait(10)
except Exception, e:
print e
我发现它有一个带有提到的ID的链接,它似乎到达它(浏览器上的点出现)但没有关闭广告......因此,下面的元素是不可达的。 我的问题是:
当弹出窗口存在时,异常' ...在点上无法点击...'正在崛起, 提前致谢 :-) 此站点的示例是:http://www.iswinoujscie.pl
答案 0 :(得分:0)
尝试等到" element_to_be_clickable
":
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
driver.get("http://www.iswinoujscie.pl/")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID,"CloseLink"))).click()
答案 1 :(得分:0)
:-)(下一步)工作解决方案是:
# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.proxy import Proxy, ProxyType
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from time import sleep
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
def my_proxy(PROXY):
"""
"""
prox = Proxy()
prox.proxy_type = ProxyType.MANUAL
prox.http_proxy = PROXY
prox.socks_proxy = PROXY
prox.ssl_proxy = PROXY
capabilities = webdriver.DesiredCapabilities().FIREFOX
capabilities["marionette"] = False
prox.add_to_capabilities(capabilities)
# in my Debian Linux, Firefox is here:
binary = FirefoxBinary('/usr/lib/firefox-esr/firefox-esr')
return webdriver.Firefox(firefox_binary=binary,
capabilities=capabilities)
# PROXY settings:
# -----------------------------
# http://www.freeproxylists.net/
# -----------------------------
driver = my_proxy('52.163.62.13:80')
# to test, if proxy working:
# driver.get("http://whatismyip.otg") # "https://www.iplocation.net")
# exit()
driver.get("http://www.iswinoujscie.pl/artykuly/51291")
# check if expected page is open:
assert "iswinoujscie.pl" in driver.title
# with test as end-user:
try:
if EC.alert_is_present():
print 'EC.alert_is_present()'
WebDriverWait(driver,5).until(EC.element_to_be_clickable((By.ID, "CloseLink"))).click()
else:
print 'hmm... alert not present'
except Exception, e:
print '-->', e
edit_name = driver.find_element_by_id("nickname")
edit_name.clear()
edit_name.send_keys(u"marinio")
tarea_content = driver.find_element_by_id("commentContent")
tarea_content.clear()
tarea_content.send_keys(u"Ale tu fajna pogoda :-) a jak u was?")
button_send = driver.find_element_by_id("submit")
# only after alert-adverb is closed:
button_send.click()
# or with JSexecutor:
driver.execute_script("document.getElementById('submit').click()")
'''
expected reply:
-----------
[...]
Komentarz zostanie dodany
[...]
'''
WebDriverWait(driver, 10).until(EC.text_to_be_present_in_element((By.XPATH, "//body"), u'Komentarz zostanie dodany'))
# driver.close() # close webbrowser
感谢@DurdenP @JeffC的帮助