关闭弹出窗口Python Selenium



我正试图使用Selenium访问此网站上的"下载csv"按钮。https://fplreview.com/team-planner/#forecast_table.当我第一次点击网站时,我需要输入一个"团队ID"并点击提交,这很好,但随后会出现一个弹出广告,我无法关闭它。我尝试了几种主要使用XPATH的方法,但它说按钮不在那里,尽管我添加了一个睡眠计时器来等待页面加载等。我的最终目标是使用请求来完成这项工作,但我正在尝试首先使用Selenium使其工作。谢谢下面是我的代码

`
from selenium import webdriver

driver = webdriver.Chrome()
driver.get('https://fplreview.com/team-planner/#forecast_table')

team_id = driver.find_element_by_name('TeamID')
team_id.send_keys(123)
team_id.submit()

# click close button on ad.
ad_path = '//*[@id="butt"]/html/body/div[2]/div[3]/div/div/div/div[1]/div/article/div[2]/div/div[18]/div/div/div[3]/button'
button = driver.find_element_by_xpath(ad_path)
button.click()

# export csv
export_button = driver.find_element_by_id('exportbutton')
export_button.click()

driver.quit()
`

生成的错误

`

raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="butt"]/html/body/div[2]/div[3]/div/div/div/div[1]/div/article/div[2]/div/div[18]/div/div/div[3]/button"}

`

需要等待几次才能使其工作:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time

driver = webdriver.Chrome()
driver.get('https://fplreview.com/team-planner/#forecast_table')
team_id = driver.find_element_by_name('TeamID')
team_id.send_keys(123)
team_id.submit()
# wait for the ad to load
WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.ID, 'orderModal_popop')))
# hide the ad
driver.execute_script("jQuery('#orderModal_popop').modal('hide');")
# export csv
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[2]/div[3]/div/div/div/div[1]/div/article/div[2]/div/button[6]')))
export_button = driver.find_element_by_xpath('/html/body/div[2]/div[3]/div/div/div/div[1]/div/article/div[2]/div/button[6]')
export_button.click()
# wait for download
time.sleep(3)
driver.quit()

我试了试,也得到了同样的错误。似乎程序等待的时间不够长,对我来说,它甚至在按钮加载之前就崩溃了,这可能是导致错误的原因。无论在哪里设置webdriver.implicitly_wait('time'),它都会在加载按钮之前崩溃。我建议使用显式等待,如下所示:这里。遗憾的是,我自己没有来使用它,所以我不能建议如何准确地使用它,但这似乎是这个问题的正确用途

确保找到正确的关闭按钮。这将找到id为"0"的所有元素;关闭";并点击第二个元素。试图关闭第一个元素将引发一个"0";ElementNotInteractiableException";。

button = driver.find_elements_by_xpath("//*[@id='close']")
button[1].click()

使用显式等待&更正按钮的路径

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
path = "//div[@id='orderModal_popop']/div[@class='modal-dialog']/div[@id='teamcolours']/div[@class='modal-header']/button[@id='close']"
button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable(
(By.XPATH, path)
)
)

这需要等待10秒钟才能点击正确的关闭按钮。

嘿,所以我试着用这个修复广告问题

button = driver.find_element_by_xpath("//*[@id='close']")
sleep(1)
button.click()

最新更新