Warm tip: This article is reproduced from serverfault.com, please click

Close pop up Window Python Selenium

发布于 2020-11-29 11:38:24

I'm trying to access a 'download csv' button on this website using Selenium. https://fplreview.com/team-planner/#forecast_table. When I first click on the site I need to enter a 'Team ID' and click submit which is fine but then a popup ad appears and I cannot close it. I've tried a few approaches mainly using XPATH but it says the button is not there eventhough I add a sleep timer to wait for page to load etc. My end goal is to do this using requests but I'm trying to get it working using Selenium first. Thanks. Below is my code

`
    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()

`

The error this generates

`

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"}

`

Questioner
Robben
Viewed
0
Shar 2020-11-29 21:17:15

Several waits are needed to make it work:

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()